Demystify Next.js middleware and Edge functions
Aug 24, 2023Middleware functions sit between the request and response cycle. They have the ability to alter, redirect, or terminate an HTTP request. While middleware is a concept used in many web frameworks, its implementation in Next.js is unique due to its reliance on Edge functions.
For those who'd like to dive deep with hands-on code, you can find all the relevant code on GitHub under the title "Middleware and Edge Functions in Next.js 13."
Middleware Explained
Hi, I'm Alexa. Today, I'll guide you through creating middleware functions in Next.js. The approach Next.js takes to middleware diverges from other frameworks like Express, hence this dedicated video.
At its core, middleware comprises functions that run between the request and response. These functions can access the request and response objects. For instance, similar to our Next API handler, this function interacts with these very objects.
Middleware can modify, redirect, or even halt an HTTP request. For example, if authentication is needed before accessing a specific endpoint, the middleware can prevent unauthorized users from even reaching that endpoint. They'll be either redirected to a login page or their request will be terminated immediately.
It's also worth noting that multiple middleware functions can be chained together, operating either on a single route or before it. However, Next.js middleware stands out due to its execution on the "edge". This means that the functions are deployed on various servers worldwide, ensuring rapid response times. Whenever a user sends a request, the corresponding edge function operates on the nearest server, geographically. Though this brings about swift responses, it's not without limitations – which we'll discuss further in this video.
Creating the Middleware.js File
To begin with middleware in Next.js, you should create a middleware.js
file at the same level as your 'Pages' directory. Ensure you avoid prefixes like underscores.
Here's how you can set it up:
export function middleware(request) {
// ... your code here ...
import { NextResponse } from 'next/server';
console.log("Hello from middleware");
return NextResponse.next();
}
Upon running this setup, every visited route on your app, for instance, localhost:3000, would trigger the "Hello from middleware" log.
Matching URLs
By default, Next.js middleware runs on every route. But what if you only want it to operate on specific routes? Here's how you can achieve that using the config
constant:
export const config = {
matcher: "/api/*"
}
With this, the middleware will only be active for routes prefixed with /api
.
Creating POST-only Middleware
Here's an example of a middleware function ensuring only POST requests access a route:
if (request.method !== "POST") {
return new NextResponse("Cannot access this endpoint with a GET", { status: 400 });
}
Edge Functions
Next.js middleware operates on Edge functions, a feature you cannot turn off. The edge runtime has its own unique properties, and notably, doesn't support many npm packages. For instance, incorporating the 'json web token' in your middleware function would trigger an error. To navigate this, you can either:
- Opt for packages compatible with the edge runtime.
- Shift your logic to another endpoint and invoke that endpoint from your middleware.
Using NextFetchEvent
The NextFetchEvent
can be employed in your middleware, allowing you to fetch data, then wait for the response before proceeding. Here's an example:
export function middleware(request, event) {
event.waitUntil(
fetch("/api/hello")
.then(response => response.json())
.then(data => console.log(data))
);
// ... your code here ...
}
In conclusion, I hope this video was informative. I faced numerous challenges with Next.js middleware, especially regarding edge functions. If there's anything I might have overlooked, please point it out in the comments. Thanks for tuning in, and don't forget to like, subscribe, and catch me in the next video!
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sed sapien quam. Sed dapibus est id enim facilisis, at posuere turpis adipiscing. Quisque sit amet dui dui.
Stay connected with news and updates!
Join our mailing list to receive the latest news and updates from our team.
Don't worry, your information will not be shared.
We hate SPAM. We will never sell your information, for any reason.