Next.js Discord

Discord Forum

saving data in cookies

Unanswered
Toyger posted this in #help-forum
Open in Discord
ToygerOP
so I'm a little confused on how to save stuff in cookies. I used some library called cookie-cutter or something and that saved it, but when I go to use it, I get some error like "Error: Invariant: Method expects to have requestAsyncStorage, none available"

8 Replies

ToygerOP
import { cookies } from 'next/headers';

export const client = new Class({ token: cookies().get('TOKEN')!.toString() });
I think it has to do with how it's defined but I have to export it from a separate file
otherwise I get some weird error about only being able to export functions
ToygerOP
alr I'm using cookies-next now and it gives me undefined on the server which makes sense but idk what to do now
ToygerOP
bump
@Toyger import { cookies } from 'next/headers'; export const client = new Class({ token: cookies().get('TOKEN')!.toString() });
if you want to instantiate a client in the server with a param from cookies, it is better to give the cookie value as a param and call cookies from the route itself:
import { cookies } from 'next/headers'
 
export default function Page() {
  const token = cookies().get('token')
  const client = getClient(token)
  return '...'
}

// in your client file
export const getClient = (token) => new Class({ token })
ToygerOP
alr, I'll try again
yeah, that seems to work. the way you defined token is a little weird because it's a RequestCookie so I needed to use .value but this works, thanks