#Client Cookie is not working

7 messages · Page 1 of 1 (latest)

nocturne flint
#

Hey guys. I'm trying to make cookie and originally, I created cookie via next/headers but the problem is that's based on the server.

import {NextRequest, NextResponse} from "next/server";
import {cookies} from "next/headers";

export async function GET(req: NextRequest) {
    let cookieStore = cookies();
    let uuid = cookieStore.get("motion-user");

    return NextResponse.json({"uuid": uuid});
}

export async function POST(req: NextRequest, res: NextResponse) {
    const data = await req.json();
    let cookieStore = cookies();

    cookieStore.set("client", data.uuid);

    return NextResponse.json({});
}

So I tried to create client side cookie

import {NextRequest, NextResponse} from "next/server";
import {cookies} from "next/headers";
import {setCookie} from "cookies-next";


export async function GET(req: NextRequest) {
    let cookieStore = cookies();
    let uuid = cookieStore.get("motion-user");

    return NextResponse.json({"uuid": uuid});
}

export async function POST(req: NextRequest, res: NextResponse) {
    const data = await req.json();

    setCookie("client", data.uuid, { req, res, maxAge: 60 * 6 * 24 });
    return NextResponse.json({});
}

but the error said :

 TypeError: Cannot read properties of undefined (reading 'set')
[NEXT]     at setCookie (webpack-internal:///(rsc)/./node_modules/cookies-next/lib/index.js:110:25)
[NEXT]     at POST (webpack-internal:///(rsc)/./app/api/client/route.ts:21:60)
[NEXT]     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
[NEXT]     at async D:\Project\web\Motion\motion-web\node_modules\next\dist\compiled\next-server\app-route.runtime.dev.js:6:63809
[NEXT]     at async eU.execute (D:\Project\web\Motion\motion-web\node_modules\next\dist\compiled\next-server\app-route.runtime.dev.js:6:53964)
[NEXT]     at async eU.handle (D:\Project\web\Motion\motion-web\node_modules\next\dist\compiled\next-server\app

how can I make client side cookie?

wanton hullBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

frail bridge
#

how can I make client side cookie?
cookies arent meant to be set on client-side.
its supposed to be a way for server to store server-side data in the client

#

why do you want to create "client-side cookie"?

#

you can read the cookie in server component and pass it down to a client component

#

get the cookie in server component via cookies()

nocturne flint