Producing Response
Directly responding from Middleware is supported by returning either a Response or NextResponse instance. This functionality has been available since Next.js version 13.1.0.
import { isAuthenticated } from '@lib/auth';
// Limit the middleware to paths starting with `/api/`
export const config = {
matcher: '/api/:function*',
};
export function middleware(request) {
// Call our authentication function to check the request
if (!isAuthenticated(request)) {
// Respond with JSON indicating an error message
return new Response(
JSON.stringify({ success: false, message: 'authentication failed' }),
{ status: 401, headers: { 'Content-Type': 'application/json' } }
);
}
}
Middlewares in Next.js
NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. One of its features is Middleware. In this article, we will learn about the middleware in Next.js with examples.
Table of Content
- Middleware in Next.js
- Benefits of Middleware
- Convention
- Matching Paths
- NextResponse
- Using Cookies
- Setting Headers
- CORS
- Producing Response