Next.js Middleware problems

I’m having trouble with my middleware in 2 applications.

both look like that

import type { NextRequest } from 'next/server';
import createMiddleware from 'next-intl/middleware';

import { routing } from './i18n/routing';

const intlMiddleware = createMiddleware(routing);

export function middleware(request: NextRequest) {
  const response = intlMiddleware(request);

  const initialTheme = request.cookies.get('theme')?.value;
  let theme = 'light';
  if (initialTheme === 'dark') {
    theme = 'dark';
  }

  response.headers.set('x-theme', theme);

  return response;
}

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

On dev env it works perfectly, but on netlify, I can see the request cookies, but it doesnt set the response cookies.
then if reload the page, the theme goes to default, and same with the language if I navigate to another page.

Repos: GitHub - LucasMendoncaWF/portfolio
GitHub - LucasMendoncaWF/mp5

I’m setting the cookie this way on client side:
document.cookie = theme=${newTheme}; path=/; max-age=31536000; SameSite=Lax; Secure;
already tried with domain, without Secure, Without samesite and it never worked

I believe there’s some issue on Netlify that renders the next-intl library broken. In other words, I don’t think next-intl currently works as expected on Netlify. Here’s an old issue: Next.js + next-intl middleware not setting Link headers on Netlify. So I updated your middleware to drop the usage of next-intl and now I can see the x-theme response header being added correctly: f-146922/src/middleware.ts at master · hrishikesh-k/f-146922. You can see that here: Lucas Mendonça Portfolio.

However, I’m confused about yoour usage of the middleware to set response headers. You can directly use cookies to access the theme: f-146922/src/app/layout.tsx at master · hrishikesh-k/f-146922 which is a clearner and a better way to do what you’re attempting to.

yeah, you are right, I’ll also use cookies instead of the nextinli middleaware, thats the result if you blindly trust chatgpt and don’t think twice about the result code :sweat_smile: