Next.js Discord

Discord Forum

Middleware chain : Set cookie before the next middleware

Unanswered
California pilchard posted this in #help-forum
Open in Discord
Avatar
California pilchardOP
Im using next-intl for internationalization with NextJS 13 App router and Supabase for backend. Next-intl working fine but I wanna add a feature : when a user is connected, rather than using the language of the browser or the Accept-Language header, use the user preferred language which is stored in the supabase database
Okay there is my actual middleware.ts :
import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs'
import { NextRequest, NextResponse } from 'next/server'
import createIntlMiddleware from 'next-intl/middleware'
import { User } from './types/type.user';

const locales = ['en', 'fr'];

const intlMiddleware = createIntlMiddleware({
  locales,
  defaultLocale: 'en',
  localePrefix: 'never',
})

export async function middleware(req: NextRequest) {
  const res = NextResponse.next()
  const supabase = createMiddlewareClient({ req, res })
  const { data: { session } } = await supabase.auth.getSession();
  const { data: user } = await supabase.from('user').select('*').eq('id', session?.user.id).single() as { data: User }
  if (user) {
    res.cookies.set(
      {
        name: 'NEXT_LOCALE',
        value: user.language,
        maxAge: 365 * 24 * 60 * 60,
        path: '/',
        sameSite: 'strict',
        priority: 'medium'
    });
  }
  return intlMiddleware(req);
}

export const config = {
  matcher: ['/((?!api|_next|_vercel|.*\\..*).*)']
}


The problem is the cookie is never set if the user exist. Why ? Idk but if I do return (res) against return intlMiddleware(req) is working (but I loose the intlMiddleware so isnt the solution. So how can we set a cookie before calling intMiddelware.

0 Replies