Skip to content

Commit 56fd4a2

Browse files
docs: update listen to use port env variable
1 parent 3b7cc15 commit 56fd4a2

21 files changed

+68
-70
lines changed

.prettierrc

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
{
22
"singleQuote": true,
3-
"trailingComma": "all"
3+
"trailingComma": "all",
4+
"printWidth": 80
45
}

content/devtools/ci-cd.md

+2-4
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ async function bootstrap() {
4040

4141
await app.close();
4242
} else {
43-
await app.listen(3000);
43+
await app.listen(process.env.PORT ?? 3000);
4444
}
4545
}
4646
```
@@ -232,9 +232,7 @@ const publishOptions = {
232232
sha: process.env.CI_COMMIT_SHA,
233233
target: process.env.CI_MERGE_REQUEST_DIFF_BASE_SHA,
234234
trigger: process.env.CI_MERGE_REQUEST_DIFF_BASE_SHA ? 'pull' : 'push',
235-
branch:
236-
process.env.CI_COMMIT_BRANCH ??
237-
process.env.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME,
235+
branch: process.env.CI_COMMIT_BRANCH ?? process.env.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME,
238236
};
239237
```
240238

content/devtools/overview.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ async function bootstrap() {
99
const app = await NestFactory.create(AppModule, {
1010
snapshot: true,
1111
});
12-
await app.listen(3000);
12+
await app.listen(process.env.PORT ?? 3000);
1313
}
1414
```
1515

@@ -185,7 +185,7 @@ This page comes in handy when you want to identify potential issues in your appl
185185
To save a serialized graph to a file, use the following code:
186186

187187
```typescript
188-
await app.listen(3000); // OR await app.init()
188+
await app.listen(process.env.PORT ?? 3000); // OR await app.init()
189189
fs.writeFileSync('./graph.json', app.get(SerializedGraph).toString());
190190
```
191191

content/exception-filters.md

+7-4
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,10 @@ Nest provides a set of standard exceptions that inherit from the base `HttpExcep
141141
All the built-in exceptions can also provide both an error `cause` and an error description using the `options` parameter:
142142

143143
```typescript
144-
throw new BadRequestException('Something bad happened', { cause: new Error(), description: 'Some error description' })
144+
throw new BadRequestException('Something bad happened', {
145+
cause: new Error(),
146+
description: 'Some error description',
147+
});
145148
```
146149

147150
Using the above, this is how the response would look:
@@ -150,7 +153,7 @@ Using the above, this is how the response would look:
150153
{
151154
"message": "Something bad happened",
152155
"error": "Some error description",
153-
"statusCode": 400,
156+
"statusCode": 400
154157
}
155158
```
156159

@@ -278,7 +281,7 @@ To create a global-scoped filter, you would do the following:
278281
async function bootstrap() {
279282
const app = await NestFactory.create(AppModule);
280283
app.useGlobalFilters(new HttpExceptionFilter());
281-
await app.listen(3000);
284+
await app.listen(process.env.PORT ?? 3000);
282285
}
283286
bootstrap();
284287
```
@@ -394,7 +397,7 @@ async function bootstrap() {
394397
const { httpAdapter } = app.get(HttpAdapterHost);
395398
app.useGlobalFilters(new AllExceptionsFilter(httpAdapter));
396399

397-
await app.listen(3000);
400+
await app.listen(process.env.PORT ?? 3000);
398401
}
399402
bootstrap();
400403
```

content/faq/keep-alive-connections.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ async function bootstrap() {
1818
const app = await NestFactory.create(AppModule, {
1919
forceCloseConnections: true,
2020
});
21-
await app.listen(3000);
21+
await app.listen(process.env.PORT ?? 3000);
2222
}
2323

2424
bootstrap();

content/faq/multiple-servers.md

+13-15
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ const httpsOptions = {
1010
const app = await NestFactory.create(AppModule, {
1111
httpsOptions,
1212
});
13-
await app.listen(3000);
13+
await app.listen(process.env.PORT ?? 3000);
1414
```
1515

1616
If you use the `FastifyAdapter`, create the application as follows:
@@ -33,10 +33,7 @@ const httpsOptions = {
3333
};
3434

3535
const server = express();
36-
const app = await NestFactory.create(
37-
AppModule,
38-
new ExpressAdapter(server),
39-
);
36+
const app = await NestFactory.create(AppModule, new ExpressAdapter(server));
4037
await app.init();
4138

4239
const httpServer = http.createServer(server).listen(3000);
@@ -56,16 +53,17 @@ export class ShutdownObserver implements OnApplicationShutdown {
5653

5754
public async onApplicationShutdown(): Promise<void> {
5855
await Promise.all(
59-
this.httpServers.map((server) =>
60-
new Promise((resolve, reject) => {
61-
server.close((error) => {
62-
if (error) {
63-
reject(error);
64-
} else {
65-
resolve(null);
66-
}
67-
});
68-
})
56+
this.httpServers.map(
57+
(server) =>
58+
new Promise((resolve, reject) => {
59+
server.close((error) => {
60+
if (error) {
61+
reject(error);
62+
} else {
63+
resolve(null);
64+
}
65+
});
66+
}),
6967
),
7068
);
7169
}

content/faq/raw-body.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import { AppModule } from './app.module';
1717
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
1818
rawBody: true,
1919
});
20-
await app.listen(3000);
20+
await app.listen(process.env.PORT ?? 3000);
2121
```
2222

2323
To access the raw request body in a controller, a convenience interface `RawBodyRequest` is provided to expose a `rawBody` field on the request: use the interface `RawBodyRequest` type:
@@ -77,7 +77,7 @@ const app = await NestFactory.create<NestFastifyApplication>(
7777
rawBody: true,
7878
},
7979
);
80-
await app.listen(3000);
80+
await app.listen(process.env.PORT ?? 3000);
8181
```
8282

8383
To access the raw request body in a controller, a convenience interface `RawBodyRequest` is provided to expose a `rawBody` field on the request: use the interface `RawBodyRequest` type:

content/faq/serverless.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ import { AppModule } from './app.module';
3737

3838
async function bootstrap() {
3939
const app = await NestFactory.create(AppModule, { logger: ['error'] });
40-
await app.listen(3000);
40+
await app.listen(process.env.PORT ?? 3000);
4141
}
4242
bootstrap();
4343

content/first-steps.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ import { AppModule } from './app.module';
5656

5757
async function bootstrap() {
5858
const app = await NestFactory.create(AppModule);
59-
await app.listen(3000);
59+
await app.listen(process.env.PORT ?? 3000);
6060
}
6161
bootstrap();
6262
@@switch
@@ -65,7 +65,7 @@ import { AppModule } from './app.module';
6565

6666
async function bootstrap() {
6767
const app = await NestFactory.create(AppModule);
68-
await app.listen(3000);
68+
await app.listen(process.env.PORT ?? 3000);
6969
}
7070
bootstrap();
7171
```

content/fundamentals/lifecycle-events.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ async function bootstrap() {
8484
// Starts listening for shutdown hooks
8585
app.enableShutdownHooks();
8686

87-
await app.listen(3000);
87+
await app.listen(process.env.PORT ?? 3000);
8888
}
8989
bootstrap();
9090
```

content/middlewares.md

+6-4
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,7 @@ Nest middleware are, by default, equivalent to [express](https://expressjs.com/e
2020

2121
You implement custom Nest middleware in either a function, or in a class with an `@Injectable()` decorator. The class should implement the `NestMiddleware` interface, while the function does not have any special requirements. Let's start by implementing a simple middleware feature using the class method.
2222

23-
> warning **Warning** `Express` and `fastify` handle middleware differently and provide different method signatures, read more [here](/techniques/performance#middleware).
24-
23+
> warning **Warning** `Express` and `fastify` handle middleware differently and provide different method signatures, read more [here](/techniques/performance#middleware).
2524
2625
```typescript
2726
@@filename(logger.middleware)
@@ -132,7 +131,10 @@ export class AppModule {
132131
Pattern based routes are supported as well. For instance, the asterisk is used as a **wildcard**, and will match any combination of characters:
133132

134133
```typescript
135-
forRoutes({ path: 'ab*cd', method: RequestMethod.ALL });
134+
forRoutes({
135+
path: 'ab*cd',
136+
method: RequestMethod.ALL,
137+
});
136138
```
137139

138140
The `'ab*cd'` route path will match `abcd`, `ab_cd`, `abecd`, and so on. The characters `?`, `+`, `*`, and `()` may be used in a route path, and are subsets of their regular expression counterparts. The hyphen ( `-`) and the dot (`.`) are interpreted literally by string-based paths.
@@ -245,7 +247,7 @@ If we want to bind middleware to every registered route at once, we can use the
245247
@@filename(main)
246248
const app = await NestFactory.create(AppModule);
247249
app.use(logger);
248-
await app.listen(3000);
250+
await app.listen(process.env.PORT ?? 3000);
249251
```
250252

251253
> info **Hint** Accessing the DI container in a global middleware is not possible. You can use a [functional middleware](middleware#functional-middleware) instead when using `app.use()`. Alternatively, you can use a class middleware and consume it with `.forRoutes('*')` within the `AppModule` (or any other module).

content/openapi/introduction.md

+4-3
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ async function bootstrap() {
3232
const document = SwaggerModule.createDocument(app, config);
3333
SwaggerModule.setup('api', app, document);
3434

35-
await app.listen(3000);
35+
await app.listen(process.env.PORT ?? 3000);
3636
}
3737
bootstrap();
3838
```
@@ -62,14 +62,15 @@ As you can see, the `SwaggerModule` automatically reflects all of your endpoints
6262

6363
> info **Hint** To generate and download a Swagger JSON file, navigate to `http://localhost:3000/api-json` (assuming that your Swagger documentation is available under `http://localhost:3000/api`).
6464
> It is also possible to expose it on a route of your choice using only the setup method from `@nestjs/swagger`, like this:
65+
>
6566
> ```typescript
6667
> SwaggerModule.setup('swagger', app, document, {
6768
> jsonDocumentUrl: 'swagger/json',
6869
> });
6970
> ```
71+
>
7072
> Which would expose it at `http://localhost:3000/swagger/json`
7173
72-
7374
> warning **Warning** When using `fastify` and `helmet`, there may be a problem with [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP), to solve this collision, configure the CSP as shown below:
7475
>
7576
> ```typescript
@@ -187,7 +188,7 @@ export interface SwaggerCustomOptions {
187188
/**
188189
* If `true`, the selector of OpenAPI definitions is displayed in the Swagger UI interface.
189190
* Default: `false`.
190-
*
191+
*
191192
* When `true` and `swaggerOptions.urls` is provided, a dropdown labeled "Select a definition"
192193
* is shown in the Swagger UI, allowing users to select from the available API definitions
193194
* specified in the `urls` array.

content/openapi/other-features.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ async function bootstrap() {
7575
});
7676
SwaggerModule.setup('api/dogs', app, dogDocument);
7777

78-
await app.listen(3000);
78+
await app.listen(process.env.PORT ?? 3000);
7979
}
8080
bootstrap();
8181
```

content/pipes.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,7 @@ Since the `ValidationPipe` was created to be as generic as possible, we can real
430430
async function bootstrap() {
431431
const app = await NestFactory.create(AppModule);
432432
app.useGlobalPipes(new ValidationPipe());
433-
await app.listen(3000);
433+
await app.listen(process.env.PORT ?? 3000);
434434
}
435435
bootstrap();
436436
```

content/recipes/hot-reload.md

+3-6
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ declare const module: any;
6060

6161
async function bootstrap() {
6262
const app = await NestFactory.create(AppModule);
63-
await app.listen(3000);
63+
await app.listen(process.env.PORT ?? 3000);
6464

6565
if (module.hot) {
6666
module.hot.accept();
@@ -127,10 +127,7 @@ module.exports = {
127127
resolve: {
128128
extensions: ['.tsx', '.ts', '.js'],
129129
},
130-
plugins: [
131-
new webpack.HotModuleReplacementPlugin(),
132-
new RunScriptWebpackPlugin({ name: 'server.js', autoRestart: false }),
133-
],
130+
plugins: [new webpack.HotModuleReplacementPlugin(), new RunScriptWebpackPlugin({ name: 'server.js', autoRestart: false })],
134131
output: {
135132
path: path.join(__dirname, 'dist'),
136133
filename: 'server.js',
@@ -151,7 +148,7 @@ declare const module: any;
151148

152149
async function bootstrap() {
153150
const app = await NestFactory.create(AppModule);
154-
await app.listen(3000);
151+
await app.listen(process.env.PORT ?? 3000);
155152

156153
if (module.hot) {
157154
module.hot.accept();

content/security/cors.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ To enable CORS, call the `enableCors()` method on the Nest application object.
99
```typescript
1010
const app = await NestFactory.create(AppModule);
1111
app.enableCors();
12-
await app.listen(3000);
12+
await app.listen(process.env.PORT ?? 3000);
1313
```
1414

1515
The `enableCors()` method takes an optional configuration object argument. The available properties of this object are described in the official [CORS](https://github.com/expressjs/cors#configuration-options) documentation. Another way is to pass a [callback function](https://github.com/expressjs/cors#configuring-cors-asynchronously) that lets you define the configuration object asynchronously based on the request (on the fly).
@@ -19,5 +19,5 @@ Or, pass a [CORS configuration object](https://github.com/expressjs/cors#configu
1919

2020
```typescript
2121
const app = await NestFactory.create(AppModule, { cors: true });
22-
await app.listen(3000);
22+
await app.listen(process.env.PORT ?? 3000);
2323
```

content/techniques/logger.md

+6-6
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ To disable logging, set the `logger` property to `false` in the (optional) Nest
2121
const app = await NestFactory.create(AppModule, {
2222
logger: false,
2323
});
24-
await app.listen(3000);
24+
await app.listen(process.env.PORT ?? 3000);
2525
```
2626

2727
To enable specific logging levels, set the `logger` property to an array of strings specifying the log levels to display, as follows:
@@ -30,7 +30,7 @@ To enable specific logging levels, set the `logger` property to an array of stri
3030
const app = await NestFactory.create(AppModule, {
3131
logger: ['error', 'warn'],
3232
});
33-
await app.listen(3000);
33+
await app.listen(process.env.PORT ?? 3000);
3434
```
3535

3636
Values in the array can be any combination of `'log'`, `'fatal'`, `'error'`, `'warn'`, `'debug'`, and `'verbose'`.
@@ -45,7 +45,7 @@ You can provide a custom logger implementation to be used by Nest for system log
4545
const app = await NestFactory.create(AppModule, {
4646
logger: console,
4747
});
48-
await app.listen(3000);
48+
await app.listen(process.env.PORT ?? 3000);
4949
```
5050

5151
Implementing your own custom logger is straightforward. Simply implement each of the methods of the `LoggerService` interface as shown below.
@@ -93,7 +93,7 @@ You can then supply an instance of `MyLogger` via the `logger` property of the N
9393
const app = await NestFactory.create(AppModule, {
9494
logger: new MyLogger(),
9595
});
96-
await app.listen(3000);
96+
await app.listen(process.env.PORT ?? 3000);
9797
```
9898

9999
This technique, while simple, doesn't utilize dependency injection for the `MyLogger` class. This can pose some challenges, particularly for testing, and limit the reusability of `MyLogger`. For a better solution, see the <a href="techniques/logger#dependency-injection">Dependency Injection</a> section below.
@@ -148,7 +148,7 @@ const app = await NestFactory.create(AppModule, {
148148
bufferLogs: true,
149149
});
150150
app.useLogger(app.get(MyLogger));
151-
await app.listen(3000);
151+
await app.listen(process.env.PORT ?? 3000);
152152
```
153153

154154
> info **Note** In the example above, we set the `bufferLogs` to `true` to make sure all logs will be buffered until a custom logger is attached (`MyLogger` in this case) and the application initialisation process either completes or fails. If the initialisation process fails, Nest will fallback to the original `ConsoleLogger` to print out any reported error messages. Also, you can set the `autoFlushLogs` to `false` (default `true`) to manually flush logs (using the `Logger#flush()` method).
@@ -249,7 +249,7 @@ const app = await NestFactory.create(AppModule, {
249249
bufferLogs: true,
250250
});
251251
app.useLogger(new MyLogger());
252-
await app.listen(3000);
252+
await app.listen(process.env.PORT ?? 3000);
253253
```
254254

255255
> info **Hint** Alternatively, instead of setting `bufferLogs` to `true`, you could temporarily disable the logger with `logger: false` instruction. Be mindful that if you supply `logger: false` to `NestFactory.create`, nothing will be logged until you call `useLogger`, so you may miss some important initialization errors. If you don't mind that some of your initial messages will be logged with the default logger, you can just omit the `logger: false` option.

0 commit comments

Comments
 (0)