Kind: Function
Source: packages/common/decorators/http/redirect.decorator.ts
Part of: Common
Redirects request to the specified URL.
Redirect() is a route handler decorator that configures an HTTP redirect response for a controller endpoint. It stores redirect URL and optional status-code metadata that the framework reads when processing the request; a handler can also return redirect values dynamically.
Signature
tsfunction Redirect(url, statusCode: number): MethodDecorator
Parameters
| Name | Type |
|---|---|
url | any |
statusCode | number |
Returns: MethodDecorator
Diagram
mermaidgraph LR Client[HTTP Client] --> Route[Controller Route Handler] Route --> Decorator["@Redirect(url, statusCode)"] Decorator --> Metadata[Redirect Metadata] Metadata --> Router[HTTP Response Processing] Router --> Response[Redirect Response<br/>Location + 3xx Status]
Usage
tsimport { Controller, Get, Redirect } from '@nestjs/common';
@Controller('docs')
export class DocsController {
@Get()
@Redirect('https://docs.example.com', 302)
redirectToDocs() {
// Responds with a 302 redirect to https://docs.example.com
}
@Get('latest')
@Redirect()
redirectToLatestVersion() {
return {
url: 'https://docs.example.com/v2',
statusCode: 301,
};
}
}
AI Coding Instructions
- Apply
@Redirect()to controller route handlers, typically alongside HTTP method decorators such as@Get()or@Post(). - Provide a redirect URL and optional 3xx status code for static redirects; use a handler return value for request-dependent destinations.
- Prefer
301for permanent redirects and302/307for temporary redirects, based on the intended client and caching behavior. - Ensure redirect targets are validated when derived from request input to prevent open-redirect vulnerabilities.
- Do not manually write the response after using this decorator; let the framework's redirect response processing consume the metadata.
Was this page helpful?