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
Start learning this pattern below
Jump into concepts and practice - no test required
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.
Practice
middleware.ts file in a Next.js project?Solution
Step 1: Understand middleware role
Middleware runs before the request reaches pages or APIs, allowing pre-processing.Step 2: Compare with other file roles
React components handle UI, CSS files style, and database configs are separate; middleware is for request handling.Final Answer:
To run code before requests reach pages or API routes -> Option AQuick Check:
Middleware = pre-request code [OK]
- Confusing middleware with UI components
- Thinking middleware manages styles or database
- Assuming middleware runs after page rendering
middleware.ts?Solution
Step 1: Identify modern export syntax
Next.js middleware uses named export with const arrow function for clarity and modern style.Step 2: Check syntax validity
export const middleware = (req) => NextResponse.next(); usesexport const middleware = (req) => NextResponse.next();which is valid and recommended.Final Answer:
export const middleware = (req) => NextResponse.next(); -> Option CQuick Check:
Use named const export for middleware [OK]
- Using CommonJS module.exports instead of ES module export
- Using default export instead of named export
- Declaring middleware as a regular function without export
middleware.ts snippet, what will happen when a request to /dashboard is made?
import { NextResponse } from 'next/server';
export const config = { matcher: ['/dashboard'] };
export const middleware = (req) => {
if (!req.cookies.get('token')) {
return NextResponse.redirect(new URL('/login', req.url));
}
return NextResponse.next();
};Solution
Step 1: Analyze matcher and cookie check
The middleware runs only on /dashboard and checks if 'token' cookie exists.Step 2: Determine behavior based on cookie presence
If no token cookie, it redirects to /login; otherwise, it allows the request.Final Answer:
The user is redirected to /login if no token cookie is present -> Option AQuick Check:
Missing token cookie triggers redirect [OK]
- Assuming middleware runs on all routes
- Thinking request proceeds without token cookie
- Confusing redirect URL construction
middleware.ts code snippet:
import { NextResponse } from 'next/server';
export const middleware = (req) => {
if (req.cookies.token === undefined) {
return NextResponse.redirect('/login');
}
return NextResponse.next();
};Solution
Step 1: Check cookie access method
In Next.js middleware, cookies are accessed viareq.cookies.get('name'), not as object properties.Step 2: Identify error cause
Usingreq.cookies.tokenwill be undefined or cause error; correct isreq.cookies.get('token').Final Answer:
Accessing cookies directly as an object instead of using req.cookies.get() -> Option BQuick Check:
Use req.cookies.get('token') to access cookies [OK]
- Accessing cookies as properties instead of using get() method
- Forgetting to import NextResponse
- Assuming arrow functions are invalid in middleware
middleware.ts to run only on API routes starting with /api/private and redirect users without a valid auth cookie to /api/auth/unauthorized. Which config and middleware code correctly implements this?Solution
Step 1: Verify matcher pattern for API routes
The pattern/api/private/:path*correctly matches all routes under /api/private.Step 2: Check cookie access and redirect method
Usingreq.cookies.get('auth')is correct. Redirect usesNextResponse.redirect(new URL(...))with full URL.Step 3: Compare options for correctness
export const config = { matcher: ['/api/private/:path*'] }; export const middleware = (req) => { if (!req.cookies.get('auth')) { return NextResponse.redirect(new URL('/api/auth/unauthorized', req.url)); } return NextResponse.next(); }; uses correct matcher, cookie access, and redirect syntax. Others have errors like wrong cookie access, missing URL object, or rewrite instead of redirect.Final Answer:
export const config = { matcher: ['/api/private/:path*'] }; export const middleware = (req) => { if (!req.cookies.get('auth')) { return NextResponse.redirect(new URL('/api/auth/unauthorized', req.url)); } return NextResponse.next(); }; -> Option DQuick Check:
Use matcher with :path*, get() for cookies, and redirect with URL [OK]
- Using wildcard * instead of :path* in matcher
- Accessing cookies as properties instead of get()
- Using rewrite instead of redirect for unauthorized access
- Not wrapping redirect URL in new URL()
