App Router API Middleware
Show how to implement middleware with the new App Router to perform server-side checks, like authentication or redirections before rendering a page.
const express = require('express');
const app = express();
// Middleware for authentication
const checkAuth = (req, res, next) => {
// Insert your authentication logic here
const userIsAuthenticated = true; // Just for example
if (!userIsAuthenticated) {
res.status(401).send('User is not authenticated');
} else {
next();
}
};
// Middleware for redirection
const redirectionMiddleware = (req, res, next) => {
// Insert your redirection logic here
const shouldBeRedirected = false; // Just for example
if (shouldBeRedirected) {
res.redirect('/some-other-page');
} else {
next();
}
};
Defines two pieces of middleware: one for authenticating the user and another for redirecting the request. If the user is not authenticated, a 401 response is sent. If a redirection condition is met, the request is redirected to another page.
app.use(checkAuth);
app.use(redirectionMiddleware);
Applies the authentication and redirection middleware to all incoming requests.
app.get('/protected-page', (req, res) => {
// This route is protected, and user will see it only if authenticated and not redirected
res.send('Welcome to the protected page!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Creates a protected route that will only render if the user passes the authentication and redirection middleware. The server listens on port 3000.