import { NextRequest, NextResponse } from 'next/server';
const PUBLIC_FILE = /\.(.*)$/;
export async function middleware(req: NextRequest) {
if (
req.nextUrl.pathname.startsWith('/_next') ||
req.nextUrl.pathname.includes('/api/') ||
PUBLIC_FILE.test(req.nextUrl.pathname)
) {
return null;
}
// Save last visited locale as a default locale
if (req.nextUrl.locale !== 'default') {
// SET COOKIE HERE
}
if (req.nextUrl.locale === 'default') {
const locale = req.cookies.get('NEXT_LOCALE')?.value || 'en';
return NextResponse.redirect(
new URL(`/${locale}${req.nextUrl.pathname}${req.nextUrl.search}`, req.url)
);
}
return null;
}
#How to set NEXT_LOCALE cookie from my middleware?
1 messages · Page 1 of 1 (latest)
Hi @gloomy whale. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In your code, you want to set a cookie when the locale is not 'default'. You can use the ResponseCookies API to set cookies on the response. Here's how you can do it:
import { NextRequest, NextResponse } from 'next/server';
const PUBLIC_FILE = /\.(.*)$/;
export async function middleware(req: NextRequest) {
if (
req.nextUrl.pathname.startsWith('/_next') ||
req.nextUrl.pathname.includes('/api/') ||
PUBLIC_FILE.test(req.nextUrl.pathname)
) {
return null;
}
// Save last visited locale as a default locale
if (req.nextUrl.locale !== 'default') {
// SET COOKIE HERE
const response = NextResponse.next();
response.cookies.set('NEXT_LOCALE', req.nextUrl.locale);
return response;
}
if (req.nextUrl.locale === 'default') {
const locale = req.cookies.get('NEXT_LOCALE')?.value || 'en';
return NextResponse.redirect(
new URL(`/${locale}${req.nextUrl.pathname}${req.nextUrl.search}`, req.url)
);
}
return null;
}
In the code above, we're using NextResponse.next() to create a new response object, and then using response.cookies.set() to set the 'NEXT_LOCALE' cookie to the current locale. This cookie will be sent along with the response to the client.
For more information, you can refer to the Next.js documentation on Middleware (https://nextjs.org/docs/pages/building-your-application/routing/middleware).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@gloomy whale kapa.ai is still learning and improving, please let us know how it did by reacting below