Parallel routes with middleware
Setting up a middleware in Next.js to manage multiple routes and execute them in parallel, applicable for custom authentication or logging logic.
// Import necessary modules from Next.js and other dependencies
const { createRouter } = require('next-connect');
const { NextApiResponse } = require('next');
// Middleware to log request details
const logMiddleware = (req, res, next) => {
console.log(`Request made to: ${req.url}`);
next();
};
// Middleware for custom authentication
const authMiddleware = async (req, res, next) => {
// Your authentication logic here...
const isAuthenticated = true; // Replace with real authentication check
if (!isAuthenticated) {
// If the user is not authenticated, return a 401 Unauthorized response
res.status(401).end('Unauthorized');
return;
}
next();
};
// Initialize the router
const router = createRouter()
// Attach the logMiddleware to log all incoming requests
.use(logMiddleware)
// Attach the authMiddleware for authentication before processing the routes
.use(authMiddleware);
// Define a GET route handler for '/api/user'
router.get('/api/user', async (req, res) => {
// Your '/api/user' route logic here...
res.json({ user: 'John Doe' });
});
// Define a GET route handler for '/api/orders'
router.get('/api/orders', async (req, res) => {
// Your '/api/orders' route logic here...
res.json({ orders: ['Order 1', 'Order 2'] });
});
// Export the middleware to use it in Next.js API routes
module.exports = router.middleware();
This code sets up a Next.js Next-connect router with two pieces of middleware: `logMiddleware` for logging requests and `authMiddleware` for custom authentication. Both middleware are applied to every route in this router. Two parallel routes '/api/user' and '/api/orders' are created, each with its own request handler, where you would place your specific logic for those endpoints. The router is then exported, allowing it to be used in any Next.js API route file.