moshest / next-client-cookies Goto Github PK
View Code? Open in Web Editor NEWSSR and client support for cookies in Next.js 13 (app directory)
License: MIT License
SSR and client support for cookies in Next.js 13 (app directory)
License: MIT License
The technique used in the demo is dangerous, since HttpOnly cookies will be written to the document body:
https://github.com/moshest/next-client-cookies/blob/main/demo/app/layout.tsx#L17
Instead, an explicit allowlist can be used to specify which cookie names get passed to the provider.
I believe I followed all instructions correctly, but the cookie data is undefined by the time my component renders on the client. Here's a quick overview of what I'm doing. I'm using the App router, and I have a cookie that get sets through an API route on a sign in page. Then I go back to the Home page of the site and I'm wanting to check the cookie to see if it's expired from my Navbar component. As I'm sure you guessed, I'm going to use the active cookie as a flag for whether the user is logged in or not, then update the UI as needed (ex., the Navbar will show "Sign In" if the cookie is expired).
In the Navbar component, I'm attempting to inject the cookie data into the jsx just so I can see it's there, much like your example in the Github instructions. When the page loads, for a split second I see the cookie appear, then it disappears and an error is displayed, which I'll show in a moment. Also, through logging I can see that the cookie is getting retrieved server side, it's showing in the terminal, but it's not getting retrieved client side, as it's undefined in the browser console.
The cookie is getting retrieved at least on the server, so I know something's working. I'm new to NextJS development, so I'm not understanding what's going wrong here. Here's the error getting displayed:
Unhandled Runtime Error
Error: Hydration failed because the initial UI does not match what was rendered on the server.
Warning: Did not expect server HTML to contain the text node "eifjlspapeIEFhjfiels9eksghels3ahhnilk.eyJzZXNzaW9uVG9rZW4iOiJyOjllYmQ5OGM1YjAxZDhiMWZjNTc4ODczNzAxMWVkM2NkIiwiaWF0IjoxNjk4ODU1NTc4LCJleHAiOjE2OTg4NTYxNzh9.se8x2ovczG_0tA9nujZrxX7puE5UokTsyTH_aIx-_JE" in <div>.
See more info here: https://nextjs.org/docs/messages/react-hydration-error
Component Stack
div
div
nav
Navbar
./app/components/Navbar.tsx (18:84)
main
Nextjs cookies I am using it to set on my SSR post and getting it with yours but your cookies cannot get that native cookies setted but get another setted ones
Hi, I'm getting this TypeScript error when importing the server part:
Linter doesn't complain when imported from next-client-cookies/dist/server
, but that'll break the runtime.
Bit weird, since you are using TypeScript here and have things properly typed. Probably some sort of a misconfiguration here or on my end..
Here's my tsconfig.json:
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"baseUrl": ".",
"paths": {
"@/*": ["./*"]
},
"plugins": [
{
"name": "next"
}
],
"strictNullChecks": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "constants.mjs"],
"exclude": ["node_modules"]
}
I have a React hook where there is also query getter defined for an axios call. E.g.
import { useQuery } from '@tanstack/react-query';
import { useCookies } from 'next-client-cookies';
export async function fetchTasks(cookies): Promise<object[]> {
try {
const tasks =
(await axios.get({ headers: { cookies }, url: '/api/tasks'))?.data || [];
return tasks;
} catch (err) {
console.error({ error: err }, 'Failed to fetch onboarding tasks');
return [];
}
}
export function useTasks() {
const cookies = useCookies();
return useQuery(() => fetchTasks(cookies));
}
The import { useCookies } from 'next-client-cookies';
import statement causes application to crush with:
Failed to compile
./node_modules/next-client-cookies/dist/index.mjs
Error: It's currently unsupported to use "export *" in a client boundary. Please use named exports instead.
This error occurred during the build process and can only be dismissed by fixing the error.
Whenever I wrap my application in CookiesProvider
imported from "next-client-cookies/server", I receive this error.
I was not calling useCookies
or cookies
anywhere, so, what might be the problem?
I believe the httpOnly property is missing in the type definition of 'CookieAttributes'.
I am getting this error when setting the httpOnly property.
Object literal may only specify known properties, and 'httpOnly' does not exist in type 'CookieAttributes'.
I'm not sure if my usage is incorrect or not but my error is following:
Collecting page data ...Error: Invariant: cookies() expects to have requestAsyncStorage, none available. at cookies (webpack-internal:///2491:50:15) at getCookies (webpack-internal:///9491:22:36) at eval (webpack-internal:///573:16:96) at 573 (C:\Users\Alex\Desktop\GitHub\Frontend\.next\server\app\Dashboard\page.js:1:262747) at __webpack_require__ (C:\Users\Alex\Desktop\GitHub\Frontend\.next\server\webpack-runtime.js:1:146) at eval (webpack-internal:///877:57:17)
Here's my code:
"use server"
...
import { getCookies } from 'next-client-cookies/server'
const Dashboard = async () => {
const cookies = getCookies();
const userData = JSON.parse(cookies.get('userData'));
...
return(
...
)
}
export default Dashboard;
update the CookiesProvider import, the default import in VSCode is as follows:
import { CookiesProvider } from "next-client-cookies";
and the import is considered deprecated. The readme says that you should specify
import { CookiesProvider } from "next-client-cookies/server";
it took me a long time to figure out why the console was constantly displaying
⨯ node_modules\next-client-cookies\dist\hook.js (44:0) @ eval
⨯ Error: Missing <CookiesProvider>
at CreateUserPage (./src/app/admin/create-user/page.tsx:67:84)
null
Because of my inattention in the readme, I didn't understand what caused the error.
Check out the demo in this repo: https://github.com/IonelLupu/next-client-cookies
I have the main client component which sets a cookie. At the same time, I have some other component which needs that cookie value so it gets it from the cookie store.
The problem is that the component that reads the cookie is not receiving a value in the SSR step. What are the solutions here?
I try to set cookies inside "use server". But I got Error: Cookies can only be modified in a Server Action or Route Handler.
I noticed while building my application that the entire app now opted out of static generation.
After debugging the problem I concluded the cause to be wrapping the root layout with <CookieProvider>
.
In my case, I only needed client cookies on a single page, so wrapping the root was an overkill.
I think it would be beneficial to document this.
Hi Moshest, thanks for your awesome package, i have a wired error in my nextjs 14 logs and the package is working perfectly and i can see the cookie in client side but i have this error in my server side:
⨯ node_modules\next-client-cookies\dist\hook.js (44:12) @ eval
⨯ Error: Missing <CookiesProvider>
at Form_handler (./app/components/ai/form_handler.tsx:21:84)
here is my code:
"use client";
import { useCookies } from 'next-client-cookies';
export function Form_handler() {
const cookies = useCookies();
const my_token = cookies.get('token')
console.log(my_token)
return (
<section className="flex justify-center">
<div>nothing</div>
</section>
);
}
export default Form_handler;
Hi!
I'm running into the following error, any lead on how this may be solved?
Error: Could not find the module "/node_modules/.pnpm/[email protected][email protected][email protected]/node_modules/next-client-cookies/dist/provider.mjs#SecureCookiesProvider" in the React Client Manifest. This is probably a bug in the React Server Components bundler.
There's a dependency resolution error when trying to use this library with Next.js canary:
npm ERR! code ERESOLVE
--
22:37:29.375 | npm ERR! ERESOLVE could not resolve
22:37:29.375 | npm ERR!
22:37:29.376 | npm ERR! While resolving: [email protected]
22:37:29.376 | npm ERR! Found: [email protected]
22:37:29.376 | npm ERR! node_modules/next
22:37:29.376 | npm ERR! next@"^14.1.1-canary.0" from the root project
22:37:29.376 | npm ERR!
22:37:29.376 | npm ERR! Could not resolve dependency:
22:37:29.376 | npm ERR! peer next@">= 13.0.0" from [email protected]
22:37:29.376 | npm ERR! node_modules/next-client-cookies
22:37:29.376 | npm ERR! next-client-cookies@"^1.1.0" from the root project
22:37:29.376 | npm ERR!
22:37:29.376 | npm ERR! Conflicting peer dependency: [email protected]
22:37:29.377 | npm ERR! node_modules/next
22:37:29.377 | npm ERR! peer next@">= 13.0.0" from [email protected]
22:37:29.377 | npm ERR! node_modules/next-client-cookies
22:37:29.377 | npm ERR! next-client-cookies@"^1.1.0" from the root project
22:37:29.377 | npm ERR!
22:37:29.377 | npm ERR! Fix the upstream dependency conflict, or retry
22:37:29.377 | npm ERR! this command with --force or --legacy-peer-deps
22:37:29.377 | npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
I currently use --legacy-peer-deps
, but this only works locally, not when deploying to Vercel (where I can't set this flag)
Hi
i have a question why on set method options there is not option for httpOnly? the nextjs cookies has it
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.