Next.js Discord

Discord Forum

Issue with middleware response cookies

Answered
gin posted this in #help-forum
Open in Discord
Avatar
ginOP
In my middleware i set a cookie like this
response.cookies.set("tw_locale", languageToSet, {
        maxAge: 60 * 60 * 24 * 365,
        path: "/",
    });

on the first request where the cookie is not set it does successfully set it. After the middleware returns the response with the cookie the layout.tsx should render right?
my root layout =
export default async function RootLayout({
                                             children,
                                         }: Readonly<{
    children: React.ReactNode;
}>) {

    const {language, data} = await decideLanguage();


my decideLanguage function does this
export async function decideLanguage() {
    const store = cookies();


    const cookie = store.get("tw_locale")?.value as string;


    const language = languageProfiles.find((profile) => profile.shortName === cookie);

so practically it should retrieve the tw_locale cookie right? since middleware runs before everything else.
the problem is cookie returns undefined (only on the first request where it is set)
Answered by gin
Hey i fixed it with setting a custom header that contains the languagecode. then reading that if cooke is undefined
View full answer

6 Replies

Avatar
ginOP
And "languageToSet" is a valid string yes
would appreciate the help
Avatar
ginOP
bump
Avatar
ginOP
Hey i fixed it with setting a custom header that contains the languagecode. then reading that if cooke is undefined
Answer