How to Redirect Response in Express: Simple Guide
In Express, you redirect a response using the
res.redirect() method by passing the target URL as an argument. This sends a redirect status and location header to the client, instructing the browser to navigate to the new URL.Syntax
The res.redirect() method sends a redirect response to the client. It can take either a URL string or a status code and a URL string.
res.redirect(url): Redirects with default status 302 (Found).res.redirect(status, url): Redirects with a specific HTTP status code (e.g., 301 for permanent redirect).
javascript
res.redirect(url) res.redirect(status, url)
Example
This example shows a simple Express server that redirects requests from the root URL to /home. When a user visits /, the server sends a redirect response to /home.
javascript
import express from 'express'; const app = express(); const port = 3000; app.get('/', (req, res) => { res.redirect('/home'); }); app.get('/home', (req, res) => { res.send('Welcome to the Home Page!'); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
Output
Server running at http://localhost:3000
When visiting http://localhost:3000/, the browser redirects to http://localhost:3000/home and shows "Welcome to the Home Page!"
Common Pitfalls
Common mistakes when using res.redirect() include:
- Forgetting to specify the status code when a permanent redirect is needed (default is 302 temporary redirect).
- Calling
res.redirect()after sending a response, which causes errors because the response is already finished. - Using relative URLs incorrectly; always ensure the URL is valid and properly formatted.
javascript
/* Wrong: sending response before redirect */ app.get('/wrong', (req, res) => { res.send('This is wrong'); res.redirect('/home'); // Error: Can't set headers after they are sent }); /* Right: redirect without sending other response */ app.get('/right', (req, res) => { res.redirect(301, '/home'); // Permanent redirect });
Quick Reference
| Method | Description | Example |
|---|---|---|
| res.redirect(url) | Redirects with status 302 (temporary) | res.redirect('/login') |
| res.redirect(status, url) | Redirects with specified status code | res.redirect(301, '/new-url') |
Key Takeaways
Use res.redirect(url) to send a temporary redirect (status 302) to the client.
Use res.redirect(status, url) to specify a different HTTP status code like 301 for permanent redirects.
Do not send any other response before calling res.redirect(), or it will cause errors.
Ensure the redirect URL is correct and properly formatted to avoid navigation issues.
Redirects tell the browser to load a different page by sending a special HTTP response.