Next JS Course
Middleware in Next JS allows you to run code before a request is completed, enabling you to perform tasks such as authentication, logging, redirects, and more. Middleware can be applied to specific routes or the entire application.
Creating Middleware in Next JS
Next JS introduced the concept of Middleware in version 12. Middleware can be created in the middleware.js or middleware.ts file at the root of your project.
Let's see an example of middleware that logs the requested URL and the current date and time
// middleware.js import { NextResponse } from 'next/server'; export function middleware(request) { console.log(`Request URL: ${request.nextUrl}`); console.log(`Request Time: ${new Date().toISOString()}`); return NextResponse.next(); }
Applying Middleware to Specific Routes
You can apply middleware to specific routes by using a matcher. This helps to restrict the middleware to certain paths.
// middleware.js import { NextResponse } from 'next/server'; export function middleware(request) { console.log(`Request URL: ${request.nextUrl}`); console.log(`Request Time: ${new Date().toISOString()}`); return NextResponse.next(); } // Applying middleware only to `/api` routes export const config = { matcher: '/api/:path*', };
Authentication Middleware
A common use case for middleware is to check if a user is authenticated before allowing access to certain routes.
// middleware.js import { NextResponse } from 'next/server'; export function middleware(request) { const token = request.cookies.get('auth-token'); if (!token) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); } // Apply the middleware to routes that need authentication export const config = { matcher: ['/dashboard/:path*', '/settings/:path*'], };
Logging Middleware
You might want to log details about incoming requests for monitoring or debugging purposes.
// middleware.js import { NextResponse } from 'next/server'; export function middleware(request) { console.log(`Request Method: ${request.method}`); console.log(`Request URL: ${request.nextUrl}`); console.log(`Request Headers: ${JSON.stringify(request.headers)}`); console.log(`Request IP: ${request.ip}`); return NextResponse.next(); } // Apply the middleware to all routes export const config = { matcher: '/:path*', };
Redirect Middleware
Redirect middleware can be used to redirect users based on certain conditions, such as outdated URLs or specific user roles.
// middleware.js import { NextResponse } from 'next/server'; export function middleware(request) { const url = request.nextUrl; if (url.pathname === '/old-path') { return NextResponse.redirect(new URL('/new-path', request.url)); } return NextResponse.next(); } // Apply the middleware to all routes export const config = { matcher: '/:path*', };