Consider this NestJS controller method:
@Get('old-route')
redirectToNew(@Res() res: Response) {
return res.redirect('/new-route');
}What happens when a client requests /old-route?
import { Controller, Get, Res } from '@nestjs/common'; import { Response } from 'express'; @Controller() export class AppController { @Get('old-route') redirectToNew(@Res() res: Response) { return res.redirect('/new-route'); } }
Think about what res.redirect() does in Express.
The res.redirect() method sends a 302 HTTP response telling the client to request the new URL. NestJS uses Express under the hood, so this behavior applies.
Which of the following NestJS controller methods correctly sends a redirect response using decorators without accessing @Res()?
Look for the official NestJS way to redirect using decorators.
The @Redirect() decorator tells NestJS to send a redirect response. Returning nothing inside the method works fine. Returning a string or object without the decorator won't trigger a redirect.
Given this NestJS controller method:
@Get('start')
start(@Res() res: Response) {
res.redirect('/end');
return 'done';
}What is the problem with this code?
import { Controller, Get, Res } from '@nestjs/common'; import { Response } from 'express'; @Controller() export class AppController { @Get('start') start(@Res() res: Response) { res.redirect('/end'); return 'done'; } }
Think about what happens when you call res.redirect() and then return a value.
Calling res.redirect() sends a response immediately. Returning a value after that tries to send another response, which causes an error because HTTP only allows one response per request.
Consider this NestJS controller method:
@Get('go')
@Redirect('/final', 301)
go() {
return;
}What HTTP status code will the client receive?
import { Controller, Get, Redirect } from '@nestjs/common'; @Controller() export class AppController { @Get('go') @Redirect('/final', 301) go() { return; } }
Check the second argument of the @Redirect() decorator.
The second argument to @Redirect() sets the HTTP status code. Here it is 301, which means a permanent redirect.
In NestJS, what is the main reason to avoid using @Res() to send a redirect and also returning a value from the same controller method?
Think about how NestJS handles responses when @Res() is injected.
When you use @Res(), NestJS expects you to handle the entire response yourself. Returning a value in addition causes NestJS to try sending a second response, which leads to errors.