2023-05-28

How can the cookie value not be the same in the dynamic route?

I implemented a program with next js , i want to use cookies on dynamic pages , the problem is that the cookie value is inherited in other pages , this happens while each page should have its own cookie.

I want to have a button to set cookie and a Link for navigation between dynamic blog routes , when i set the cookie for example in this path /blog/2 and click the Link to go to next blog or previous blog , the cookie is inherited in other dynamic blog routes.

  • In this example , the js-cookie module is used.

Example :

// /blog/[blogId]

import Cookies from 'js-cookie';
import Link from 'next/link';
import { useRouter } from 'next/router';
import dynamic from 'next/dynamic';

function SingleBlog() {
    const router = useRouter();
    const { blogId } = router.query;

    return (
        <>
            <Link href={`/blog/${Number(blogId) + 1}`}> next blog </Link>
            <button onClick={() => Cookies.set('name', `blog${blogId}`, { path: `/blog/${blogId}` })}> set </button>
            {Cookies.get('name') && <p>cookie : {Cookies.get('name')}</p>}
        </>
    )
}

export default dynamic(() => Promise.resolve(SingleBlog), { ssr: false });

  • If the page is refreshed, we see the cookie value and if the navigation between the blog pages is inside the program, the cookie value that is displayed is a fixed value in any case.

What is the solution ?



No comments:

Post a Comment