Recall & Review
beginner
What is the purpose of the
middleware.ts file in Next.js?The
middleware.ts file runs code before a request is completed. It can modify requests, responses, or redirect users. It helps control access and behavior globally or for specific routes.Click to reveal answer
beginner
Where should the
middleware.ts file be placed in a Next.js project?The
middleware.ts file should be placed in the root of the Next.js project, at the same level as pages or app folders. This placement ensures it runs for all routes by default.Click to reveal answer
intermediate
How do you export middleware in
middleware.ts?You export a function named <code>middleware</code> that takes a <code>NextRequest</code> and returns a <code>NextResponse</code> or modifies the request. Example: <br><pre>import { NextRequest, NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
return NextResponse.next();
}</pre>Click to reveal answer
intermediate
What is the role of the
matcher export in middleware.ts?The
matcher export defines which paths the middleware should run on. It is an array of strings or patterns. This helps limit middleware to specific routes instead of all routes.Click to reveal answer
beginner
Why should middleware code be fast and lightweight?
Middleware runs on every matching request before the page loads. Slow middleware delays the whole page response. Keeping it fast ensures a smooth user experience and better performance.
Click to reveal answer
Where do you place the
middleware.ts file in a Next.js project?✗ Incorrect
The
middleware.ts file should be placed in the root folder to apply middleware globally or selectively.What does the
middleware function receive as its first argument?✗ Incorrect
The middleware function receives a
NextRequest object representing the incoming request.How do you limit middleware to run only on certain routes?
✗ Incorrect
The
matcher export defines which routes the middleware applies to.What should middleware return to continue the request without changes?
✗ Incorrect
Returning
NextResponse.next() tells Next.js to continue processing the request normally.Why is it important to keep middleware code fast?
✗ Incorrect
Middleware runs on every matching request, so slow code delays the whole page response.
Explain the purpose and placement of the
middleware.ts file in a Next.js project.Think about how middleware acts like a gatekeeper for requests.
You got /4 concepts.
Describe how to limit middleware execution to certain routes using the
matcher export.Consider how you tell middleware where to work.
You got /4 concepts.