0
0
NestJSframework~5 mins

Redirect responses in NestJS

Choose your learning style9 modes available
Introduction

Redirect responses send users to a different URL automatically. This helps guide users to the right page without them clicking links.

After a user logs in, send them to their dashboard page.
When a page is moved, redirect visitors to the new location.
Send users to a login page if they try to access a protected route.
After submitting a form, redirect to a confirmation page.
Redirect from a root URL to a main homepage.
Syntax
NestJS
import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';

@Controller()
export class AppController {
  @Get('old-path')
  redirectToNew(@Res() res: Response) {
    return res.redirect('/new-path');
  }
}

Use the @Res() decorator to access the response object.

Call res.redirect() with the URL to send a redirect response.

Examples
Redirects the user to the '/home' URL.
NestJS
res.redirect('/home');
Redirects with status code 301 (permanent redirect) to '/new-location'.
NestJS
res.redirect(301, '/new-location');
Redirects to an external website URL.
NestJS
res.redirect('https://example.com');
Sample Program

This controller has two routes. Visiting '/old-page' sends a redirect response to '/new-page'. Visiting '/new-page' shows a welcome message.

NestJS
import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';

@Controller()
export class RedirectController {
  @Get('old-page')
  redirectToNewPage(@Res() res: Response) {
    return res.redirect('/new-page');
  }

  @Get('new-page')
  newPage() {
    return 'Welcome to the new page!';
  }
}
OutputSuccess
Important Notes

Using @Res() disables automatic response handling, so you must send the response yourself.

Redirect status codes like 301 (permanent) or 302 (temporary) can be specified as the first argument.

Always test redirects in a browser or with tools like curl to confirm behavior.

Summary

Redirect responses send users to a different URL automatically.

Use res.redirect() inside a controller method with @Res().

You can specify the redirect URL and optionally the status code.