ZANREAL logoNEMO
Packages

Supabase

NEMO middleware functions for Supabase

Installation

Integrate Supabase with your project using the official guides:

Supabase Quickstart or Supabase Next.js App

We will only make one small change to make it work with NEMO.

Integrate NEMO with Supabase middleware

Create _middleware.ts.

Create a new file in your projects lib or supabase directory called _middleware.ts.

And paste middleware code that you've copied from the Supabase documentation.

It should look something like this:

@/lib/supabase/middleware.ts
import { createServerClient } from '@supabase/ssr';
import { type NextRequest, NextResponse } from 'next/server';
 
export async function updateSession(request: NextRequest) {
  let supabaseResponse = NextResponse.next({
    request,
  })
 
  const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
    {
      cookies: {
        getAll() {
          return request.cookies.getAll()
        },
        setAll(cookiesToSet) {
          cookiesToSet.forEach(({ name, value, options }) => request.cookies.set(name, value))
            supabaseResponse = NextResponse.next({
            request,
          })
          cookiesToSet.forEach(({ name, value, options }) =>
            supabaseResponse.cookies.set(name, value, options)
          )
        },
      },
    }
  );
 
  // refreshing the auth token
  await supabase.auth.getUser();
 
  return supabaseResponse;
}

Replace middleware.ts code

We need to edit primary middleware.ts file to use the new middleware function.

@/middleware.ts
import { type MiddlewareConfig, type GlobalMiddlewareConfig, createNEMO } from '@rescale/nemo';
import { updateSession } from '@/lib/supabase/middleware';
 
const globalMiddlewares: GlobalMiddlewareConfig = {
  before: updateSession, // REMEMBER TO IMPORT updateSession
}
 
const middlewares: MiddlewareConfig = {
  '/': [
    async (request) => {
      console.log('There is NEMO', request.nextUrl.pathname);
    },
  ],
};
 
export const middleware = createNEMO(middlewares, globalMiddlewares);
 
export const config = {
  matcher: ['/((?!_next/|_static|_vercel|[\\w-]+\\.\\w+).*)'],
};

(Optional) Add user infomation to context

To add user information to the context, you can use the following code:

@/lib/supabase/middleware.ts
// imports
 
export async function updateSession(request, { storage }) {  
 
  // prev code
 
  // refreshing the auth token
  await supabase.auth.getUser(); 
  const { user } = await supabase.auth.getUser(); 
 
  // add user to storage
  storage.set('user', user ?? undefined); 
 
  return supabaseResponse;
}

On this page