Questions
What is middleware and how do you use it in Next.js?
The Scenario
You are a frontend engineer at a social media company. You are building a new application that needs to have a feature that redirects users from a certain country to a different version of the website.
You could implement this logic in each page, but this would be repetitive and would violate the DRY (Don’t Repeat Yourself) principle.
The Challenge
Explain what middleware is in Next.js and how you would use it to solve this problem. What are the key benefits of using middleware?
A junior engineer might not be aware of middleware. They might try to solve this problem by adding the redirect logic to each page, which would be a verbose and difficult to maintain solution.
A senior engineer would know that middleware is the perfect tool for this job. They would be able to explain what middleware is and how to use it to implement a redirect based on the user's country.
Step 1: Understand What Middleware Is
Middleware is a function that is executed before a request is completed. It can be used to modify the response by rewriting, redirecting, adding headers, or streaming HTML.
Step 2: Create a Middleware Function
To create a middleware function, you just need to create a middleware.js (or .ts) file in your pages directory.
Here’s how we can create a middleware function to redirect users from a certain country:
// pages/_middleware.js
import { NextResponse } from 'next/server'
export function middleware(req) {
const { geo } = req
if (geo.country === 'US') {
return new Response('Blocked for legal reasons', { status: 451 })
}
return NextResponse.next()
}In this example, we check the user’s country from the geo property of the request. If the user is from the US, we return a 451 status code. Otherwise, we continue to the next middleware or to the page.
The Benefits of Using Middleware
| Benefit | Description |
|---|---|
| Centralization | You can centralize your logic in a single place, instead of having to repeat it in multiple pages. |
| Flexibility | Middleware can be used to implement a variety of different features, such as authentication, A/B testing, and internationalization. |
Practice Question
You want to run a piece of code before every request to a specific set of pages. Which of the following would you use?