Nest.Js Redirect from a controller to another

17,009

Solution 1

Redirecting from one controller to another works with res.redirect(target). As target, you have to combine the paths from the controller and the route annotation:

@Controller('books') + @Get('greet') = /books/greet

@Controller()
export class AppController {
  @Get()
  redirect(@Res() res) {
    return res.redirect('/books/greet');
  }
}

@Controller('books')
export class AnotherController {
  @Get('greet')
  greet() {
    return 'hello';
  }
}

See this running example here:

Edit Redirect-Controller

Solution 2

Another way to do that is to use the @Redirect() decorator as documented here: https://docs.nestjs.com/controllers#redirection

This should work as well:

@Controller()
export class AppController {
  @Get()
  @Redirect('books')
  redirect(){}
}

@Controller('books')
export class AnotherController {
  @Get()
  getBooks() {
    return 'books';
  }
}
Share:
17,009
Edeph
Author by

Edeph

I'm a student in programming willing and eager to learn more .

Updated on June 15, 2022

Comments

  • Edeph
    Edeph almost 2 years

    So I have this module:

    @Module({
      imports: [],
      controllers: [AppController, AnotherController],
      providers: [],
    })
    

    And in AppController on some route I want to do res.redirect('/books') where /books is a route found in AnotherController.

    For some reason this doesn't work and I can't figure out if it's not supported or I'm doing it wrong.

  • Edeph
    Edeph almost 5 years
    This is indeed the correct answer. What is weird is that I keep my controllers in 2 separate files and it doesn't work like that. It only works if i don't specify anything in the @Controller() and then write @Get('/books/greet'). Which is weird because this is something that I understand is by default.
  • Edeph
    Edeph almost 5 years
    Apparently having another route like /books/:id written as @Get(':id') was breaking it.
  • Ctfrancia
    Ctfrancia almost 3 years
    note, this only works with GET method, any url provided with otherwise will be sent with a get first causing the endpoint not to be found