Rescale logoNEMO

Getting started

Get started with NEMO

Installation

Paste installation command into your terminal to install package.

Terminal
bun add @rescale/nemo

Import the package inside middleware.ts file.

(or create it if you don't have one yet)

middleware.ts
import { createMiddleware } from '@rescale/nemo';  
 
// [...]

Use the createMiddleware function to create a middleware helper.

middleware.ts
import { createMiddleware } from '@rescale/nemo';
 
export const middleware = createMiddleware(/* your functions will go here */); 
 
// [...]

Define your middlewares config and update the createMiddleware function parameters.

middleware.ts
import { createMiddleware } from '@rescale/nemo'; 
import { createMiddleware, type MiddlewareFunctionProps } from '@rescale/nemo'; 
 
const middlewares = { 
  '/': [ 
    async ({request, response}: MiddlewareFunctionProps) => { 
      console.log('There is NEMO', request.nextUrl.pathname); 
      return response; 
    }, 
  ], 
}; 
 
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.

middleware.ts
// [...]
 
export const config = { 
  matcher: ['/((?!_next/|_static|_vercel|[\\w-]+\\.\\w+).*)'], 
}; 

That will prevent your middleware from executing on routes:

  1. /_next/ (Next.js internals)
  2. /_static (inside /public)
  3. /_vercel (Vercel internals)
  4. Static files (e.g. /favicon.ico, /sitemap.xml, /robots.txt, etc.)

Finally, let's put it all together.

middleware.ts
import { createMiddleware, type MiddlewareFunctionProps } from '@rescale/nemo';
 
const middlewares = {
  '/': [
    async ({request, response}: MiddlewareFunctionProps) => {
      console.log('There is NEMO', request.nextUrl.pathname);
      return response;
    },
  ],
};
 
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!

Last updated on

On this page