0
0
NextJSframework~3 mins

Why Middleware.ts file convention in NextJS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how one file can save you from repeating the same code on every page!

The Scenario

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.

The Problem

Manually repeating authentication checks everywhere is tiring, easy to forget, and makes your code messy and hard to update.

The Solution

The middleware.ts file lets you run code once for many routes automatically, keeping your app clean and consistent.

Before vs After
Before
if (!userLoggedIn) { redirect('/login') } // repeated in every page
After
import { NextResponse } from 'next/server';

export function middleware(request) {
  if (!request.cookies.get('token')) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
}
What It Enables

You can control access and run shared logic for many pages in one place, making your app easier to build and maintain.

Real Life Example

Protecting all dashboard pages so only logged-in users can see them, without adding checks to each page file.

Key Takeaways

Manual checks everywhere cause repetition and errors.

middleware.ts centralizes shared logic for routes.

This keeps your app clean, consistent, and easier to update.