📖 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
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
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
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
Hint
Check that AppController is exported so NestJS can use it.
Practice
(1/5)
1. What is the primary purpose of using res.redirect() in a NestJS controller?
easy
A. To send the user to a different URL automatically
B. To send JSON data as a response
C. To handle database queries
D. To log user requests
Solution
Step 1: Understand the function of res.redirect()
This method is used to send an HTTP redirect response to the client, telling the browser to go to a different URL.
Step 2: Compare with other options
Options A, B, and C describe other unrelated tasks like logging, sending JSON, or querying databases, which are not the purpose of res.redirect().
Final Answer:
To send the user to a different URL automatically -> Option A
Quick Check:
Redirect means sending user to another URL [OK]
Hint: Redirect means sending user to a new URL [OK]
Common Mistakes:
Confusing redirect with sending JSON response
Thinking redirect handles database operations
Assuming redirect logs requests
2. Which of the following is the correct way to inject the response object to use res.redirect() in a NestJS controller method?
easy
A. Use @Body() decorator
B. Use @Req() decorator
C. Use @Res() decorator
D. Use @Param() decorator
Solution
Step 1: Identify the decorator for response object
In NestJS, @Res() is used to inject the response object to access methods like redirect().
Step 2: Verify other decorators
@Req() is for request, @Body() is for request body data, and @Param() is for route parameters, none provide the response object.
Final Answer:
Use @Res() decorator -> Option C
Quick Check:
Response object injection = @Res() [OK]
Hint: Use @Res() to get response object for redirect [OK]
B. Returning a string after res.redirect() causes an error
C. Missing await before res.redirect()
D. res.redirect() must be called without parameters
Solution
Step 1: Understand res.redirect() behavior
Calling res.redirect() sends the response immediately. Returning a value after sending response causes NestJS to throw an error because response is already sent.
Step 2: Check other options
Status code 301 is valid for permanent redirect, no await needed as redirect is synchronous, and redirect requires parameters.
Final Answer:
Returning a string after res.redirect() causes an error -> Option B
Quick Check:
Don't return after sending response [OK]
Hint: Don't return after res.redirect() sends response [OK]
Common Mistakes:
Thinking 301 is invalid status code
Adding await unnecessarily
Calling redirect without parameters
5. You want to create a NestJS controller method that redirects users to different URLs based on a query parameter 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?
D. async redirect(@Query('type') type: string, @Res() res) {
if (type === 'admin') {
res.redirect('/admin/dashboard');
} else if (type === 'user') {
res.redirect(301, '/user/home');
} else {
res.redirect('/');
}
}
Solution
Step 1: Check correct usage of res.redirect()
Calling 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.
Step 2: Analyze each option
async redirect(@Query('type') type: string, @Res() res) {
if (type === 'admin') {
return res.redirect('/admin/dashboard');
} else if (type === 'user') {
return res.redirect(301, '/user/home');
} else {
return res.redirect('/');
}
} incorrectly uses return res.redirect(), which can cause errors. async redirect(@Query('type') type: string, @Res() res) {
if (type === 'admin') {
res.redirect(302, '/admin/dashboard');
} else if (type === 'user') {
res.redirect('/user/home');
} else {
res.redirect(302, '/');
}
return 'Redirected';
} returns a string after redirect, causing errors. async redirect(@Query('type') type: string, @Res() res) {
if (type === 'admin') {
return res.redirect(302, '/admin/dashboard');
} else if (type === 'user') {
return res.redirect('/user/home');
} else {
return res.redirect(302, '/');
}
} mixes return and missing status codes. async redirect(@Query('type') type: string, @Res() res) {
if (type === 'admin') {
res.redirect('/admin/dashboard');
} else if (type === 'user') {
res.redirect(301, '/user/home');
} else {
res.redirect('/');
}
} calls res.redirect() properly without return and uses correct status codes.
Final Answer:
The code that calls res.redirect() properly without return and with correct status codes -> Option D
Quick Check:
Call res.redirect() without return, specify status if needed [OK]
Hint: Call res.redirect() without return; specify status as first argument [OK]
Common Mistakes:
Returning after res.redirect() causing errors
Not specifying status code correctly
Returning strings after sending response
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.