Performance: Redirect responses
Redirect responses affect page load speed by causing additional HTTP requests and delays before the final content loads.
import { Controller, Get } from '@nestjs/common'; @Controller() export class AppController { @Get('old-route') redirectOld() { return 'New content here'; } @Get('new-route') newRoute() { return 'New content here'; } }
import { Controller, Get, Res } from '@nestjs/common'; import { Response } from 'express'; @Controller() export class AppController { @Get('old-route') redirectOld(@Res() res: Response) { res.redirect('/new-route'); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Redirect response causing client-side navigation | Minimal | 0 | Delayed paint due to extra request | [X] Bad |
| Directly serving final content without redirect | Minimal | 0 | Paint happens faster | [OK] Good |
res.redirect() in a NestJS controller?res.redirect()res.redirect().res.redirect() in a NestJS controller method?@Res() is used to inject the response object to access methods like redirect().@Req() is for request, @Body() is for request body data, and @Param() is for route parameters, none provide the response object.@Res() decorator -> Option Casync redirectToGoogle(@Res() res) {
res.redirect('https://google.com');
}
What will happen when this method is called?res.redirect() sends a 302 status code by default, redirecting the user to the given URL.@Get('go')
async go(@Res() res) {
res.redirect(301, 'https://example.com');
return 'Redirecting';
}res.redirect() sends the response immediately. Returning a value after sending response causes NestJS to throw an error because response is already sent.type. If type is 'admin', redirect to '/admin/dashboard' with status 302; if 'user', redirect to '/user/home' with status 301; otherwise, redirect to '/' with status 302. Which code snippet correctly implements this?res.redirect() with URL only defaults to 302 status. To specify status, pass it as first argument. The method sends response immediately, so no return is needed.Pass the test and this pattern moves unknown