0
0
NestJSframework~15 mins

Redirect responses in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Redirect Responses in NestJS
📖 Scenario: You are building a simple web server using NestJS. Sometimes, you want to send users to a different web page automatically. This is called a redirect. For example, when a user visits the home page, you want to send them to the welcome page.
🎯 Goal: Create a NestJS controller that redirects users from the root URL / to /welcome using the proper NestJS redirect response method.
📋 What You'll Learn
Create a controller class named AppController.
Add a method named redirectToWelcome that handles GET requests to /.
Use the @Redirect decorator to redirect to /welcome with status code 302.
Add a method named welcome that handles GET requests to /welcome and returns a simple welcome message.
💡 Why This Matters
🌍 Real World
Redirects are common in web apps to guide users to updated pages or login screens automatically.
💼 Career
Understanding redirects is important for backend developers working with web frameworks like NestJS to manage user navigation and HTTP responses.
Progress0 / 4 steps
1
Create the controller class and import decorators
Create a controller class called AppController. Import Controller, Get, and Redirect from @nestjs/common. Add the @Controller() decorator to the class.
NestJS
Need a hint?

Use import { Controller, Get, Redirect } from '@nestjs/common'; and add @Controller() above the class.

2
Add a redirect method for the root URL
Inside AppController, add a method named redirectToWelcome. Use the @Get('/') decorator and the @Redirect('/welcome', 302) decorator above it. The method should return nothing.
NestJS
Need a hint?

Use @Get('/') and @Redirect('/welcome', 302) decorators above the method named redirectToWelcome.

3
Add a welcome method to handle /welcome route
Inside AppController, add a method named welcome with the @Get('/welcome') decorator. The method should return the string 'Welcome to the site!'.
NestJS
Need a hint?

Use @Get('/welcome') above the welcome method that returns the welcome string.

4
Export the controller and finalize the code
Make sure the AppController class is exported using export class AppController. This completes the controller setup for redirect responses.
NestJS
Need a hint?

Check that AppController is exported so NestJS can use it.