Error reading a cookie set with document.cookie in loaders #12725
-
I am using shadcn ui with the sidebar component and it has this behaviour where you can persist the sidebar state in the cookie, this is how it typically sets the cookie with document.cookie: const SIDEBAR_COOKIE_NAME = 'sidebar:state'
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
...
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}` But in my loader, when I get the cookies with import * as cookie from 'cookie'
export const loader = async ({ request }: Route.LoaderArgs) => {
const user = await requireUser(request)
console.log({
parsedCookie: cookie.parse(request.headers.get('cookie') ?? ''),
})
}
// parsed cookie does not contain the sidebar state cookie
{
parsedCookie: C <[Object: null prototype] {}> {
'CH-time-zone': 'Atlantic/St_Helena',
'CH-reduced-motion': 'no-preference',
'CH-prefers-color-scheme': 'dark',
}
}
// when I run document.cookie on the client, this is the result:
// console.log(document.cookie) or just run document.cookie in the browser console
CH-time-zone=Atlantic%2FSt_Helena; CH-reduced-motion=no-preference; CH-prefers-color-scheme=dark; sidebar:state=false |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
Why dont use cookie helpers from framework https://reactrouter.com/explanation/sessions-and-cookies ? |
Beta Was this translation helpful? Give feedback.
-
@discoverlance-com did you find an elegant solution to this? |
Beta Was this translation helpful? Give feedback.
@vniehues, I am not sure why but I basically, changed the cookie name from
sidebar:state
to justsidebar
in the sidebar component and this worked. It looks like the cookie set on the document having the name with a colon in it was the issue? Could it be a bug in react router reading the cookie from the request headers or parsing of the cookie? I did read that the HTTP Cookie Specification (RFC 6265) does not explicitly ban the use of colons in cookie names but some servers, browsers and frameworks might have compatibility issues.I tried to actually create a react router cookie with the
createCookie
function that uses a colon in the cookie name and that did work though so it could be comp…