Discover how one file can save you from repeating the same code on every page!
Why Middleware.ts file convention in NextJS? - Purpose & Use Cases
Imagine you want to check user login status on every page of your Next.js app by writing the same code in every page file.
Manually repeating authentication checks everywhere is tiring, easy to forget, and makes your code messy and hard to update.
The middleware.ts file lets you run code once for many routes automatically, keeping your app clean and consistent.
if (!userLoggedIn) { redirect('/login') } // repeated in every page
import { NextResponse } from 'next/server'; export function middleware(request) { if (!request.cookies.get('token')) { return NextResponse.redirect(new URL('/login', request.url)); } }
You can control access and run shared logic for many pages in one place, making your app easier to build and maintain.
Protecting all dashboard pages so only logged-in users can see them, without adding checks to each page file.
Manual checks everywhere cause repetition and errors.
middleware.ts centralizes shared logic for routes.
This keeps your app clean, consistent, and easier to update.