React / Next.js

Next.js Middleware & Auth

Middleware, NextAuth.js, JWT, session management, protected routes, RBAC

22 interview questionsยท
Mid-Level
1

What is middleware in Next.js?

Answer

Next.js middleware is code that runs before a request is processed, allowing you to modify the response, redirect, add headers, or block access. It runs on the Edge Runtime for optimal performance. Typically used for authentication, geolocation, or logging.

2

Where to place the middleware file in a Next.js project with App Router?

Answer

The middleware.ts (or .js) file must be placed at the project root, at the same level as the app folder. Next.js automatically detects this file and executes it for all routes. Alternatively, it can be placed in the src folder if the project uses this structure.

3

How to define the routes on which middleware executes?

Answer

Using the matcher configuration in middleware allows specifying concerned routes via path patterns. By default, middleware executes on all routes except static files. The matcher supports wildcards and regex for precise control of targeted routes.

4

What is the main advantage of using NextAuth.js for authentication?

5

How to protect a route with Next.js middleware?

+19 interview questions

Master React / Next.js for your next interview

Access all questions, flashcards, technical tests, code review exercises and interview simulators.

Start for free