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 like this:
import { createServerClient } from '@supabase/ssr'
import { NextResponse } from 'next/server'
export async function updateSession(request) {
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
}Integrate supabase middleware with NEMO
We need to change params implementation in updateSession function to use MiddlewareFunctionProps type.
import { type MiddlewareFunctionProps } from '@rescale/nemo';
// prev imports...
export async function updateSession(request) {
export async function updateSession({ request, forward }: MiddlewareFunctionProps) {
// prev code...
return supabaseResponse
forward(supabaseResponse)
}Replace middleware.ts code
We need to edit primary middleware.ts file to use the new middleware function.
import { createMiddleware, forward, type MiddlewareFunctionProps } from '@rescale/nemo';
const globalMiddlewares = {
before: updateSession, // REMEMBER TO IMPORT updateSession
}
const middlewares = {
'/': [
async ({ request }: MiddlewareFunctionProps) => {
console.log('There is NEMO', request.nextUrl.pathname);
},
],
};
export const middleware = createMiddleware(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:
// imports
export async function updateSession({ request, context }: MiddlewareFunctionProps) {
// prev code
// refreshing the auth token
await supabase.auth.getUser()
// add user to context
context.set('user', user ?? undefined);
return supabaseResponse
}