Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Middleware.ts File Convention in Next.js
📖 Scenario: You are building a Next.js app that needs to run some code before every page loads. This is useful for things like checking if a user is logged in or redirecting them to a special page.
🎯 Goal: Create a middleware.ts file in a Next.js app that runs on every request and redirects users from the homepage to a welcome page.
📋 What You'll Learn
Create a middleware.ts file with the correct export
Use the Next.js NextResponse to handle redirects
Check the request URL pathname to decide when to redirect
Export a config object to specify which paths the middleware runs on
💡 Why This Matters
🌍 Real World
Middleware in Next.js apps helps run code before pages load, like redirects or authentication checks.
💼 Career
Understanding middleware is important for building secure and user-friendly web apps with Next.js.
Progress0 / 4 steps
1
Create the middleware function
Create a file named middleware.ts and write a function called middleware that takes a request parameter.
NextJS
Hint
Start by importing NextResponse from next/server and create the middleware function.
2
Check the request URL pathname
Inside the middleware function, create a variable called pathname that gets the pathname from request.nextUrl.
NextJS
Hint
Use request.nextUrl.pathname to get the current path the user is visiting.
3
Redirect from homepage to /welcome
Inside the middleware function, add an if statement that checks if pathname is exactly "/". If yes, return NextResponse.redirect(new URL('/welcome', request.url)).
NextJS
Hint
Use NextResponse.redirect with a new URL to send users from the homepage to /welcome.
4
Add middleware config for matching paths
After the middleware function, export a constant called config with a matcher array that includes "/" and "/welcome".
NextJS
Hint
The config export tells Next.js which paths to run the middleware on. Use matcher with an array of paths.
Practice
(1/5)
1. What is the primary purpose of the middleware.ts file in a Next.js project?
easy
A. To run code before requests reach pages or API routes
B. To define React components for UI rendering
C. To store global CSS styles
D. To configure database connections
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 A
Quick Check:
Middleware = pre-request code [OK]
Hint: Middleware runs before pages or APIs handle requests [OK]
Common Mistakes:
Confusing middleware with UI components
Thinking middleware manages styles or database
Assuming middleware runs after page rendering
2. Which of the following is the correct way to export a middleware function in middleware.ts?
easy
A. export default function middleware(req) { return NextResponse.next(); }
B. export function middleware(req) { NextResponse.next(); }
C. export const middleware = (req) => NextResponse.next();
D. module.exports = function middleware(req) { return NextResponse.next(); }
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(); uses export const middleware = (req) => NextResponse.next(); which is valid and recommended.
Final Answer:
export const middleware = (req) => NextResponse.next(); -> Option C
Quick Check:
Use named const export for middleware [OK]
Hint: Use named const arrow function export for middleware [OK]
Common Mistakes:
Using CommonJS module.exports instead of ES module export
Using default export instead of named export
Declaring middleware as a regular function without export
3. Given this middleware.ts snippet, what will happen when a request to /dashboard is made?
A. Missing import of NextRequest from 'next/server'
B. Accessing cookies directly as an object instead of using req.cookies.get()
C. Using arrow function instead of regular function
D. Not exporting config.matcher for route matching
Solution
Step 1: Check cookie access method
In Next.js middleware, cookies are accessed via req.cookies.get('name'), not as object properties.
Step 2: Identify error cause
Using req.cookies.token will be undefined or cause error; correct is req.cookies.get('token').
Final Answer:
Accessing cookies directly as an object instead of using req.cookies.get() -> Option B
Quick Check:
Use req.cookies.get('token') to access cookies [OK]
Hint: Use req.cookies.get('name') to read cookies in middleware [OK]
Common Mistakes:
Accessing cookies as properties instead of using get() method
Forgetting to import NextResponse
Assuming arrow functions are invalid in middleware
5. You want your 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?