Impossible to set a cookie on route.ts #74326
-
Link to the code that reproduces this issuehttps://github.com/NatigAgarzayev/prizmaorm To ReproduceHi, I use the newest versions: I can't set cookie on route.ts Path: app/api/user/signup/route.ts
However I did the same in a server component CookieSend.tsx and it works fine. Current vs. Expected behaviorI expected the cookie to be set on the browser, but many attempts to solve were failed. Provide environment information"dependencies": {
"@prisma/client": "^6.1.0",
"bcrypt": "^5.1.1",
"jsonwebtoken": "^9.0.2",
"next": "15.1.2",
"react": "^19.0.0",
"react-dom": "^19.0.0"
}, Which area(s) are affected? (Select all that apply)Documentation, Parallel & Intercepting Routes Which stage(s) are affected? (Select all that apply)next dev (local), Other (Deployed) Additional contextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments 5 replies
-
You need to include the There's a code snippet in the docs that demonstrates this: https://nextjs.org/docs/app/building-your-application/routing/route-handlers#cookies |
Beta Was this translation helpful? Give feedback.
-
Unfortunatelly it didn't work for me. I posted the latest version of my code on github (link provided above).
|
Beta Was this translation helpful? Give feedback.
-
Here’s the code for implemented user signup, which successfully sets a cookie: 'use server'
import { prisma } from '@/lib/prisma'
import { cookies } from 'next/headers'
import jwt from 'jsonwebtoken'
export async function POST(request: Request) {
const { name, email, password } = await request.json()
const user = await prisma.user.create({ data: { name, email, password } })
if (user) {
const token = jwt.sign({ email }, process.env.SECRET_KEY!, { expiresIn: '1h' })
const cookieStore = await cookies()
cookieStore.set('token', token, { httpOnly: true, path: '/' })
return new Response(JSON.stringify(user), { status: 201 })
} else {
return new Response('User creation failed', { status: 500 })
}
} Key Points:
|
Beta Was this translation helpful? Give feedback.
-
Adding //'use server' Removed use server
import { prisma } from '@/lib/prisma'
import type { NextRequest } from 'next/server'
import jwt from 'jsonwebtoken'
export async function POST(request: NextRequest) {
const { name, email, password } = await request.json()
const res = await prisma.user.create({
data: {
name,
email,
password
}
})
if (res) {
const token = jwt.sign({ email }, process.env.SECRET_KEY!, {
expiresIn: '1h'
})
return new Response(
JSON.stringify(res),
{
headers: {
'Set-Cookie': `token=${token}; HttpOnly; SameSite=Strict`,
},
}
)
}
else {
return new Response(res)
}
} |
Beta Was this translation helpful? Give feedback.
-
I recorded a screen video and posted on YouTube. |
Beta Was this translation helpful? Give feedback.
-
I tested your repo, and it works fine. You just need to remove 'use server' from the handleSignUp method and make the signup page a client component. "use client";
import React from "react";
export default function page() {
const handleSignUp = async (formData: FormData) => {
const name = formData.get("name") as string;
const email = formData.get("email") as string;
const password = formData.get("password") as string;
if (!name || !email || !password) {
return;
}
const res = await fetch("http://localhost:3000/api/user/signup", {
method: "POST",
body: JSON.stringify({
name,
email,
password,
}),
});
console.log(res);
};
return (
<div className="flex justify-center items-center h-screen bg-slate-200">
<form
action={handleSignUp}
className="flex flex-col gap-2 items-center text-slate-900"
>
<h1 className="text-2xl">Sign up</h1>
<label htmlFor="name">Name:</label>
<input
className="p-2 outline-none "
type="text"
name="name"
id="name"
/>
<label htmlFor="email">Email:</label>
<input
className="p-2 outline-none "
type="email"
name="email"
id="email"
/>
<label htmlFor="password">Password:</label>
<input
className="p-2 outline-none "
type="password"
name="password"
id="password"
/>
<button type="submit" className="p-2 border border-slate-900">
Sign Up
</button>
</form>
</div>
);
} |
Beta Was this translation helpful? Give feedback.
I tested your repo, and it works fine. You just need to remove 'use server' from the handleSignUp method and make the signup page a client component.