Sling Academy
Home/Node.js/How to Redirect to Another URL in NestJS

How to Redirect to Another URL in NestJS

Last updated: December 31, 2023

Overview

In today’s web applications, redirection is a common tactic for guiding users through different parts of an application based on certain conditions or events. With NestJS, a fast-growing Node.js framework, redirecting can be both seamless and straightforward. This tutorial aims to explore various methods and best practices for redirection in NestJS!

Basic Redirection

To start off with redirection in NestJS, you usually work within the context of a controller and its route handlers. The most basic form is to use the Redirect decorator on a controller method to specify a static URL to redirect to.

@Controller('example')
export class ExampleController {
  @Get('go-to-nest')
  @Redirect('https://nestjs.com', 302)
  goToNest() {
    // Maybe some other logic here
  }
}

Note that the Redirect decorator takes two arguments; the URL to redirect to, and the HTTP status code which by default is 302 (Found), indicating a temporary redirection.

Dynamic Redirection

Sometimes you might want to dynamically construct the destination URL. This can be achieved by returning an object with url and statusCode properties from your route handler.

@Controller('dynamic')
export class DynamicController {
  @Get('user/:userId')
  findUser(@Param('userId') userId: string) {
    // Some logic to find user
    const userExists = true; // Assume the user exists
    if (userExists) {
      return { url: `https://userpage.com/${userId}`, statusCode: 302 };
    } else {
      // Handle the case when user does not exist
    }
  }
}

This method provides more flexibility and lets you redirect based on runtime variables and conditions.

Advanced Redirect Techniques

For scenarios that require an advanced level of control, you may opt for a programmatic approach using the Response object from Express.js, which NestJS makes use of under the hood.

@Controller('advanced')
export class AdvancedController {
  @Get('external/:siteId')
  externalRedirect(@Response() res: Res, @Param('siteId') siteId: string) {
    const urlMap = {
      '1': 'https://firstsite.com',
      '2': 'https://secondsite.com',
      // Other site mappings...
    };
    const redirectUrl = urlMap[siteId] || 'https://defaultsite.com';
    res.redirect(redirectUrl);
  }
}

In this case, we’re injecting the response object directly into our handler and using Express’s redirect method. This gives us complete control over the response and allows for highly configurable redirection logic.

Handling Redirection Asynchronously

In real-world applications, you might need to perform an asynchronous operation before deciding the URL to redirect to. NestJS route handlers can handle asynchronous operations seamlessly with both Promise and async/await patterns.

@Controller('async-redirection')
export class AsyncRedirectionController {
  @Get('docs/:docId')
  async redirectToDocumentation(@Param('docId') docId: string) {
    const documentationUrl = await this.fetchDocumentationUrl(docId);
    if (documentationUrl) {
      return { url: documentationUrl, statusCode: 301 };
    } else {
      // Handle missing documentation
    }
  }

  private async fetchDocumentationUrl(docId: string): Promise {
    // Assume there's an asynchronous operation to get the URL
    // This is just a mock
    return `https://docs.example.com/${docId}`;
  }
}

With the async/await syntax, you can write asynchronous code as if it were synchronous, which keeps the logic more readable and maintainable.

Conclusion

To conclude, NestJS provides a variety of ways to handle redirection, from basic to more advanced patterns. Whether you are defining static paths, constructing dynamic URLs or integrating complex asynchronous operations, understanding and utilizing these redirection strategies will enhance your application’s flow and improve the user experience. Remember, redirection can be a powerful tool when used wisely within your web application’s navigation strategy.

Next Article: How to Bulk Redirect URLs in NestJS

Previous Article: NestJS Error: Can’t Resolve Dependencies of the JWT_MODULE_OPTIONS

Series: Nest.js Tutorials: From Basics to Advanced

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates