tezvyn:

What is Next.js Middleware and a real-world auth use case?

AI-drafted, machine-checkedSource: nextjs.orgbeginner

This tests request interception before a route renders. A good answer defines Middleware as pre-request code using NextRequest and NextResponse, often on the Edge Runtime, with auth redirects as an example.

WHAT THIS TESTS: This question checks if you understand where Middleware sits in the request lifecycle and how it differs from route handlers or client-side guards. The interviewer wants to hear that it intercepts traffic before a request completes, not during or after React renders, and that you can use it for cross-cutting concerns like authentication.

A GOOD ANSWER COVERS: First, define Middleware as code that executes before a request reaches application routes, operating on NextRequest and returning NextResponse. Second, mention that it can run on the Edge Runtime, giving it low latency and access to request headers, cookies, and geolocation. Third, give a concrete pattern like authentication: inspect the incoming request for a valid session token, and if it is missing, issue a redirect to a login page or rewrite the request to a public fallback. Fourth, note the file-system convention that places it at the project root and that it can be configured to match or skip specific paths using a matcher config.

COMMON WRONG ANSWERS: Confusing Middleware with API Routes is a major red flag because API Routes handle requests at a dedicated endpoint, whereas Middleware intercepts traffic before routing happens. Another mistake is saying Middleware runs after React renders or that it can perform heavy database queries directly, since Edge Runtime constraints limit available Node APIs. Claiming it only works in the Pages Router or that it replaces Server Component auth entirely is also incorrect.

LIKELY FOLLOW-UPS: How would you conditionally apply Middleware only to certain routes while ignoring static assets? How do you securely validate a JWT at the edge without leaking secrets? What is the behavioral difference between a rewrite and a redirect inside Middleware? When would a layout-level Server Component auth check be preferable to Middleware?

ONE CONCRETE EXAMPLE: An e-commerce site wants to protect its checkout pages. In the Middleware file, the function receives a NextRequest object, reads an auth cookie from the request headers, and checks for its presence. If the cookie is absent, the function returns NextResponse.redirect(new URL('/login', request.url)). If the cookie exists, it returns NextResponse.next() so the request proceeds to the checkout route. This keeps checkout server components free of auth boilerplate and pushes the access decision to the edge.

Read the original → nextjs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.