Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Next.js
Next.jsmedium

What is Next.js Middleware good for (and what are its limitations)?

Tags
#middleware#edge#redirect
Back to categoryPractice quiz

Answer

Middleware runs before a route (often at the edge) and can redirect/rewrite (e.g., locale routing, auth gates). It should be lightweight and has runtime limitations compared to full Node.js (not all APIs are available).

Advanced answer

Deep dive

Next.js Middleware runs *before* your route handler/page code and can execute at the edge. It’s ideal for request-level concerns that must happen early:

  • redirects/rewrites (locale routing, legacy URL migrations),
  • auth gates (redirect unauthenticated users),
  • adding/normalizing headers,
  • lightweight A/B testing or geo-based routing.

Example

// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(req: NextRequest) {
  const loggedIn = Boolean(req.cookies.get('session'))
  if (!loggedIn && req.nextUrl.pathname.startsWith('/admin')) {
    const url = req.nextUrl.clone()
    url.pathname = '/login'
    return NextResponse.redirect(url)
  }
  return NextResponse.next()
}

Limitations

  • Often Edge runtime: limited Node.js APIs (no `fs`, many native modules won’t work).
  • Must be fast: it can run for many requests.
  • Not a replacement for backend logic; avoid heavy DB calls and long computations.

Common pitfalls

  • Applying middleware to every path (including static assets) instead of using matchers.
  • Doing authorization only in middleware; still enforce it in server actions/route handlers.
  • Putting too much logic in middleware and increasing latency across the app.

Related questions

Next.js
Middleware in Next.js: what is it good for and what are its limitations?
#nextjs#middleware#edge
Next.js
Edge runtime vs Node.js runtime in Next.js — when choose which?
#edge#runtime#nodejs