Next.js Discord

Discord Forum

can't get set cookies from middleware in page.jsx

Unanswered
Pteromalid wasp posted this in #help-forum
Open in Discord
Pteromalid waspOP
trying to set an 'x-session-state' = expired cookie so i can show a toast once the session is expired however i'm unable to get that cookie in my page.jsx, it just shows null

middleware:
export async function middleware(request) {
    ...
    if (sessionCookie) {
        const { data, error } = await verifySession()
        // invalid/expired session - redirect to /auth, add x-session-state = expired to headers
        if (error) {
            console.log(`[middleware] - invalid/expired session: ${error}`);
            const response = NextResponse.redirect(new URL('/auth', request.url))
            // response.headers.set('x-session-state', 'expired')
            response.cookies.set('x-session-state', 'expired', {
                httpOnly: true,
                secure: process.env.NODE_ENV === 'production'
            });
            console.log(`[middleware] - INVALID SESSION RESPONSE COOKIES: ${response.cookies}`);
            return response
        }
...


page.jsx:
export default async function Home() {
    // const requestHeaders = await headers();
    // const sessionState = requestHeaders.get('x-session-state') || null
    // console.log(`[Home] - sessionState: ${sessionState}`);
    // const { data } = sessionState !== 'expired' ? await getApiAccountData() : { data: null };
    // // const { data } = sessionState !== 'expired' && sessionState !== null ? await getApiAccountData() : { data: null };
    // console.log(`[Home] - userData: ${data}`);

    const requestCookies = await cookies()
    const sessionStateCookie = requestCookies.get('x-session-state')?.value || null
    console.log(`[Home] - sessionStateCookie: ${sessionStateCookie}`);

    return (
        <>
            <AuthWrapper sessionState={sessionStateCookie}>
                <p>home</p>
            </AuthWrapper>
        </>
    );
}

tried setting it as a header at first but can't get them from redirect so trying with cookies, still can't get it...

14 Replies

@Pteromalid wasp trying to set an 'x-session-state' = expired cookie so i can show a toast once the session is expired however i'm unable to get that cookie in my page.jsx, it just shows null middleware: jsx export async function middleware(request) { ... if (sessionCookie) { const { data, error } = await verifySession() // invalid/expired session - redirect to /auth, add x-session-state = expired to headers if (error) { console.log(`[middleware] - invalid/expired session: ${error}`); const response = NextResponse.redirect(new URL('/auth', request.url)) // response.headers.set('x-session-state', 'expired') response.cookies.set('x-session-state', 'expired', { httpOnly: true, secure: process.env.NODE_ENV === 'production' }); console.log(`[middleware] - INVALID SESSION RESPONSE COOKIES: ${response.cookies}`); return response } ... page.jsx: jsx export default async function Home() { // const requestHeaders = await headers(); // const sessionState = requestHeaders.get('x-session-state') || null // console.log(`[Home] - sessionState: ${sessionState}`); // const { data } = sessionState !== 'expired' ? await getApiAccountData() : { data: null }; // // const { data } = sessionState !== 'expired' && sessionState !== null ? await getApiAccountData() : { data: null }; // console.log(`[Home] - userData: ${data}`); const requestCookies = await cookies() const sessionStateCookie = requestCookies.get('x-session-state')?.value || null console.log(`[Home] - sessionStateCookie: ${sessionStateCookie}`); return ( <> <AuthWrapper sessionState={sessionStateCookie}> <p>home</p> </AuthWrapper> </> ); } tried setting it as a header at first but can't get them from redirect so trying with cookies, still can't get it...
Japanese flying squid
when sending code in discord do it like this its much easier to read for others
tsx stands for the programming extension you can use jsx
@Pteromalid wasp trying to set an 'x-session-state' = expired cookie so i can show a toast once the session is expired however i'm unable to get that cookie in my page.jsx, it just shows null middleware: jsx export async function middleware(request) { ... if (sessionCookie) { const { data, error } = await verifySession() // invalid/expired session - redirect to /auth, add x-session-state = expired to headers if (error) { console.log(`[middleware] - invalid/expired session: ${error}`); const response = NextResponse.redirect(new URL('/auth', request.url)) // response.headers.set('x-session-state', 'expired') response.cookies.set('x-session-state', 'expired', { httpOnly: true, secure: process.env.NODE_ENV === 'production' }); console.log(`[middleware] - INVALID SESSION RESPONSE COOKIES: ${response.cookies}`); return response } ... page.jsx: jsx export default async function Home() { // const requestHeaders = await headers(); // const sessionState = requestHeaders.get('x-session-state') || null // console.log(`[Home] - sessionState: ${sessionState}`); // const { data } = sessionState !== 'expired' ? await getApiAccountData() : { data: null }; // // const { data } = sessionState !== 'expired' && sessionState !== null ? await getApiAccountData() : { data: null }; // console.log(`[Home] - userData: ${data}`); const requestCookies = await cookies() const sessionStateCookie = requestCookies.get('x-session-state')?.value || null console.log(`[Home] - sessionStateCookie: ${sessionStateCookie}`); return ( <> <AuthWrapper sessionState={sessionStateCookie}> <p>home</p> </AuthWrapper> </> ); } tried setting it as a header at first but can't get them from redirect so trying with cookies, still can't get it...
Japanese flying squid
so the problem is sessionStateCookie in your page.tsx is null and not the value it should be right?
@Japanese flying squid so the problem is sessionStateCookie in your page.tsx is null and not the value it should be right?
Pteromalid waspOP
yes, i originally tried to set it in the response headers but that doesn't persist for redirects and i read that cookies will but that does not seem to be the case either unless i'm mistaken
Japanese flying squid
have you tried to see in your browser if the cookie exist?
Pteromalid waspOP
don't see it
Japanese flying squid
do you get the console.log([middleware] - invalid/expired session: ${error}); when opening the site
Pteromalid waspOP
yes

"GET /api/auth/verify_session HTTP/1.1" 401 -
[verifySession] - error: [object Object], session invalid/expired, deleting cookie
[middleware] - invalid/expired session: User is not authenticated.
[middleware] - request url: http://localhost:3000/auth
[middleware] - referer: http://localhost:3000/
 ✓ Compiled /auth in 213ms (736 modules)
[Auth] - sessionStateCookie: null
[Auth] - sessionStateHeader: null
Japanese flying squid
mhmm this is weird
idk wait for a helper
Pteromalid waspOP
i'm wondering if it has to do with the redirect? like should i not be setting a cookie in the response?
Pteromalid waspOP
if i remove the redirect in middleware and just do NextResponse.next() and then add the cookie in the response i can get the cookie in page.jsx

const response = NextResponse.next()
response.cookies.set('x-session-state', 'expired', {
                httpOnly: true,
                secure: process.env.NODE_ENV === 'production',
                path: '/'
                // sameSite: 'lax'
            });
            return response


"GET /api/auth/verify_session HTTP/1.1" 401 -
[verifySession] - error: [object Object], session invalid/expired, deleting cookie
[middleware] - invalid/expired session: User is not authenticated.
[Home] - sessionStateCookie: expired


why am i not able to do that for the redirect in the middleware though?
Japanese flying squid
if the middleware is triggered in /auth too it could end in too many redirects because if session expired redirect to /auth and set cookie even tho you will arive in /auth it will redirect again this could be a problem too
Pteromalid waspOP
Once the session expires it deletes the cookie in the middleware verify session call so on redirect to /auth nothing in the middleware would execute since there’s no session token. Idk I don’t see how that causes multiple redirects