Third-party middleware like cors and helmet help protect your NestJS app and make it work well with other websites.
Third-party middleware (cors, helmet) in NestJS
import * as cors from 'cors'; import * as helmet from 'helmet'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.use(cors()); app.use(helmet()); await app.listen(3000); }
Use app.use() to add middleware in NestJS.
Both cors() and helmet() are functions that return middleware.
app.use(cors());
https://example.com.app.use(cors({ origin: 'https://example.com' }));app.use(helmet());
app.use(helmet.contentSecurityPolicy({ directives: { defaultSrc: ["'self'"] } }));This NestJS app uses cors middleware to allow cross-origin requests and helmet middleware to add security headers. When you run it, the server listens on port 3000.
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import * as cors from 'cors'; import * as helmet from 'helmet'; async function bootstrap() { const app = await NestFactory.create(AppModule); // Enable CORS for all origins app.use(cors()); // Add security headers app.use(helmet()); await app.listen(3000); console.log('Server running on http://localhost:3000'); } bootstrap();
Always configure CORS carefully to avoid exposing your API to unwanted sites.
Helmet sets many headers by default, but you can customize it for your needs.
Use browser DevTools Network tab to check CORS headers and security headers in responses.
CORS middleware controls which websites can access your API.
Helmet middleware adds security headers to protect your app.
Use app.use() in NestJS to add these middlewares easily.
Practice
cors middleware in a NestJS application?Solution
Step 1: Understand the role of CORS
CORS (Cross-Origin Resource Sharing) middleware controls which external websites or domains can access your API resources.Step 2: Differentiate from other middleware
Helmet adds security headers, logging middleware logs requests, and compression middleware compresses data. Only CORS controls access from other origins.Final Answer:
To control which websites can access your API -> Option BQuick Check:
CORS controls access = B [OK]
- Confusing CORS with Helmet's security headers
- Thinking CORS logs requests
- Assuming CORS compresses data
Solution
Step 1: Recall NestJS middleware usage
In NestJS, third-party middleware like Helmet is applied usingapp.use()with the middleware function called.Step 2: Check syntax correctness
The correct syntax isapp.use(helmet()). Other options are not valid NestJS methods or miss calling the function.Final Answer:
app.use(helmet()) -> Option CQuick Check:
Use app.use() with middleware function call = A [OK]
- Forgetting to call helmet as a function
- Using non-existent app methods like app.helmet()
- Passing helmet without parentheses
import * as helmet from 'helmet';
import * as cors from 'cors';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(cors({ origin: 'https://example.com' }));
app.use(helmet());
await app.listen(3000);
}Solution
Step 1: Analyze CORS middleware configuration
The CORS middleware is configured to allow only requests from 'https://example.com'. Requests from other origins will be blocked.Step 2: Analyze Helmet middleware effect
Helmet adds security headers to all responses to improve security.Final Answer:
Only requests from https://example.com are allowed, and security headers are added -> Option AQuick Check:
CORS origin restrict + Helmet headers = C [OK]
- Assuming all origins are allowed
- Thinking Helmet blocks requests
- Confusing CORS blocking with allowing
import * as cors from 'cors';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(cors);
await app.listen(3000);
}Solution
Step 1: Check how cors is used
The code passescorsdirectly without calling it as a function. Middleware functions must be called to return the actual middleware.Step 2: Confirm correct usage
The correct usage isapp.use(cors()). Other options are incorrect because NestJS supports app.use(), and no await is needed for middleware.Final Answer:
Missing parentheses to call cors function -> Option DQuick Check:
Middleware must be called as function = A [OK]
- Passing middleware reference without calling it
- Confusing import sources for cors
- Trying to await app.use()
https://myapp.com and add security headers. Which code snippet correctly applies both cors and helmet middleware with these requirements?Solution
Step 1: Configure CORS with specific origin
To allow only 'https://myapp.com', pass{ origin: 'https://myapp.com' }to cors middleware.Step 2: Apply Helmet middleware correctly
Helmet is applied withhelmet()to add security headers. It does not take origin options.Step 3: Verify order and correctness
Applying CORS first with correct origin, then Helmet, matches the requirements. Other options either miss origin restriction or misuse Helmet options.Final Answer:
app.use(cors({ origin: 'https://myapp.com' })); app.use(helmet()); -> Option AQuick Check:
CORS origin set + Helmet default = D [OK]
- Passing origin option to helmet instead of cors
- Allowing all origins with '*'
- Reversing middleware order causing unexpected behavior
Ready to prove it?
Pass the test and this pattern moves unknown
