简体   繁体   中英

NextJS shows I am logged out if I visit my website via a link

In the top right of my website is a little user bar component, and it just simply renders my username if I am logged in, or a "Sign In" link.

But, every single time I visit my website via a link from an external website, the "Sign In" link is rendered instead of my username. My website does not think I am logged in.

But if I just simply refresh the page with no other actions, I am showed as logged in again. When this happens, nxtCookies.getAll() seems to be empty.

Or if I visit my website by URL directly, I am showed as logged in correctly.

What could be causing this?

UserInfoBar

import React from 'react'
import Link from 'next/link'
import { getSession } from '../../lib/session'

export default async function UserInfoBar() {
    let sessionData = await getSession();

    return (
                {
                    Object.keys(sessionData).length > 0 ?
                            {sessionData.username}: <Link href='/signin'>Sign In</Link>
                }
    )
}

session

import { cookies } from 'next/headers';
import prisma from './prisma'
import jwt from 'jsonwebtoken'

export const getSession = async () => {
    const nxtCookies = cookies();

    if (nxtCookies.has('wp_session')) {
        let sessionData = jwt.verify(nxtCookies.get('wp_session').value, process.env.ACCESS_TOKEN_SECRET, async (err, user) => {
            if (!err) {
                let r = await prisma.user.findUnique({
                    where: {
                        id: user.id
                    }
                });

                if (r) {
                    return {
                        id: r?.id,
                        email: r?.email,
                        username: r?.username
                    };
                }
            }

            return false;
        });

        if (sessionData) return sessionData;
    }

    return false;
}

sign-in

( where the cookie is set )

setCookie('wp_session', token, {
    path: '/',
    maxAge: 3600 * 24 * 7 * 30,
    sameSite: true
});

The issue was with the creation of the cookie.

I was mistakenly supplying the sameSite parameter with the value of true .

The recommended value is lax .

setCookie('wp_session', token, {
    path: '/',
    maxAge: 3600 * 24 * 7 * 30,
    sameSite: 'lax'
});

Lax: Cookies are not sent on normal cross-site subrequests (for example to load images or frames into a third party site), but are sent when a user is navigating to the origin site (ie, when following a link) .

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#lax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM