Getting started
Getting started on the v1.4 line, published as @rescale/nemo. Kept for existing projects - new work should start on the current major instead.
Installation
Paste installation command into your terminal to install package.
npm install @rescale/nemoImport the package inside middleware.ts file.
(or create it if you don't have one yet)
import { createMiddleware } from '@rescale/nemo';
// [...]Use the createMiddleware function to create a middleware helper.
import { createMiddleware } from '@rescale/nemo';
export const middleware = createMiddleware(/* your functions will go here */);
// [...]Define your middlewares config and update the createMiddleware function parameters.
import { createMiddleware } from '@rescale/nemo';
import { createMiddleware, type MiddlewareFunctionProps } from '@rescale/nemo';
const middlewares = {
'/': [
async ({ request }: MiddlewareFunctionProps) => {
console.log('There is NEMO', request.nextUrl.pathname);
},
],
};
export const middleware = createMiddleware(/* your functions will go here */);
export const middleware = createMiddleware(middlewares);
// [...]After that step, you should see an There is NEMO message in your console for every request made to your application.
Optimize your middleware execution to not execute it on every signle request.
// [...]
export const config = {
matcher: ['/((?!_next/|_static|_vercel|[\\w-]+\\.\\w+).*)'],
}; That will prevent your middleware from executing on routes:
/_next/(Next.js internals)/_static(inside /public)/_vercel(Vercel internals)- Static files (e.g.
/favicon.ico,/sitemap.xml,/robots.txt, etc.)
Reed more about Next.js middleware configuration
Finally, let's put it all together.
import { createMiddleware, type MiddlewareFunctionProps } from '@rescale/nemo';
const middlewares = {
'/': [
async ({ request }: MiddlewareFunctionProps) => {
console.log('There is NEMO', request.nextUrl.pathname);
},
],
};
export const middleware = createMiddleware(middlewares);
export const config = {
matcher: ['/((?!_next/|_static|_vercel|[\\w-]+\\.\\w+).*)'],
};That's how should your middleware.ts file looks like after all steps.
Motivation
I'm working with Next.js project for a few years now, after Vercel moved multiple /**/_middleware.ts files to a single /middleware.ts file, there was a unfilled gap - but just for now. After a 2023 retro I had found that there is no good solution for that problem, so I took matters into my own hands. I wanted to share that motivation with everyone here, as I think that we all need to remember how it all started.
Hope it will save you some time and would make your project DX better!
Was this helpful?
M↓supported.