How can I set cookies following a form submission without client side javascript?
Unanswered
Oriental Scops-Owl posted this in #help-forum
Oriental Scops-OwlOP
When a user visits a site without javascript I want basic functionality to work. At minimum I want someone to be able to click submit on a form which results in a cookie be saved on their device. nextjs 15.1
Produces the error
Another approach:
Needs client side javascript and can't be converted to a server component due tot he onClick handler.
Finally,
Works as expected, but I don't like that it goes to /api/login instead of just /login. I also find it odd that I'd have to write my own route for this, since I thought one of the benefits of nextjs is handling that for you.
Hitting char limit but the login functions are just
'use server'
export async function login() {
(await cookies()).set('name','value)
}
//login-three/page.tsx
'use server'; // 'use client'; produces the same error
import { login_three } from "@/actions/login"
export default async function LoginPage() {
return (
<div>
<form action={login_three}>
<button >Login</button>
</form>
</div>
)
}
Produces the error
Error: `cookies` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
at login_two (src/actions/login.ts:18:21)
16 | export async function login_two() {
17 | try {
> 18 | (await cookies()).set('Auth-Cookie', 'abc12')
| ^
19 | return true
20 | } catch(err) {
21 | console.log(err)
Another approach:
// login-two/page.tsx
'use client';
import { login_two } from "@/actions/login"
export default async function LoginPage() {
return (
<div>
<button onClick={() => login_two()}>Login</button>
</div>
)
Needs client side javascript and can't be converted to a server component due tot he onClick handler.
Finally,
// login/page.tsx
export default async function LoginPage() {
return (
<div>
<form action="/api/login" method="POST">
<button type="submit">Test</button>
</form>
</div>
)
}
Works as expected, but I don't like that it goes to /api/login instead of just /login. I also find it odd that I'd have to write my own route for this, since I thought one of the benefits of nextjs is handling that for you.
Hitting char limit but the login functions are just
'use server'
export async function login() {
(await cookies()).set('name','value)
}