Middleware
~10 mins
- nextjs
Create Middleware
src/middleware.ts- Note: Keep the middleware.ts in
srcfolder (not inappfolder)
"use client";
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
// This function can be marked `async` if using `await` inside
export async function middleware(request: NextRequest) {
console.log("Middleware request url: " + request.url);
const path = request.nextUrl.pathname;
console.log("Path:" + path);
//return NextResponse.redirect(new URL('/login', request.url))
return NextResponse.next();
}
// See "Matching Paths" below to learn more
export const config = {
matcher: [ "/", "/login"],
}
Test url - 1
Middleware request url: http://localhost:3000/
Path: /
Test url - 2
Middleware request url: http://localhost:3000/login
Path: /login