cookies() not accessible in server actions.
Unanswered
American Fuzzy Lop posted this in #help-forum
American Fuzzy LopOP
I am trying to create an authentication flow for Pocketbase, but for some reason, whenever using the cookies() method from next/headers, I keep getting the server error:
Here is my actions.ts:
'cookies' was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-contextHere is my actions.ts:
'use server';
import { redirect } from 'next/navigation';
import { cookies } from 'next/headers';
import pb from '@/utils/pocketbaseClient';
export async function login(formData: FormData) {
const cookieStore = await cookies();
// ^^^ This is where the error occurs.
console.log('login', formData);
const email = formData.get('email') as string;
const password = formData.get('password') as string;
// TODO: server-side validation
const { token, record: model } = await pb
.collection('users')
.authWithPassword(email, password);
const cookie = JSON.stringify({ token, model });
cookieStore.set('pb_auth', cookie, {
secure: true,
path: '/',
sameSite: 'strict',
httpOnly: true,
});
redirect('/');
}
export async function logout() {
const cookieStore = await cookies();
cookieStore.delete('pb_auth');
redirect('/auth');
}