Next.js - API Middlewares
API middlewares in Next.js allow developers to add custom logic to API routes to handle authentication, request parsing, error handling, and more, before the request reaches the route handler.
1. Creating API Middlewares
To create an API middleware in Next.js, define a function that receives req and res objects representing the request and response, respectively. This function can perform pre-processing tasks such as authentication, validation, or logging before passing control to the route handler.
// middleware/auth.js
export default function middleware(req, res, next) {
// Authentication logic
if (!req.headers.authorization) {
return res.status(401).json({ error: 'Unauthorized' });
}
// Validating authentication token
const token = req.headers.authorization.split(' ')[1];
if (token !== 'SECRET_TOKEN') {
return res.status(403).json({ error: 'Forbidden' });
}
next();
}
In this example, an API middleware named auth
is created to perform authentication checks. If the request does not contain a valid authorization header or token, it responds with appropriate error status codes.
2. Applying API Middlewares
To apply an API middleware to a specific route or group of routes in Next.js, import the middleware function and use it as a middleware handler before defining the route handler.
// pages/api/protected.js
import authMiddleware from '../../middleware/auth';
export default function handler(req, res) {
// Route handler logic
res.status(200).json({ message: 'Protected resource accessed' });
}
export const middleware = [authMiddleware];
In this example, the protected
API route is protected by the auth
middleware. When a request is made to this route, it first passes through the auth
middleware, which performs authentication checks, and then proceeds to the route handler if authentication is successful.
3. Chaining API Middlewares
In Next.js, multiple middlewares can be chained together to perform a sequence of pre-processing tasks before reaching the route handler.
// middleware/logger.js
export default function loggerMiddleware(req, res, next) {
console.log('Request received:', req.method, req.url);
next();
}
// pages/api/protected.js
import authMiddleware from '../../middleware/auth';
import loggerMiddleware from '../../middleware/logger';
export default function handler(req, res) {
// Route handler logic
res.status(200).json({ message: 'Protected resource accessed' });
}
export const middleware = [loggerMiddleware, authMiddleware];
In this example, the protected
API route utilizes both logger
and auth
middlewares. When a request is made to this route, it first passes through the logger
middleware, which logs the request details, and then proceeds to the auth
middleware for authentication.
Conclusion
API middlewares in Next.js offer a flexible and powerful way to add custom logic to API routes, enabling developers to implement authentication, request processing, logging, and error handling functionalities. By applying middlewares to specific routes or chaining them together, developers can enhance the security, reliability, and performance of their Next.js applications.
Comments
Post a Comment