Next.js Discord

Discord Forum

Server Actions + Cookies

Answered
Green Kingfisher posted this in #help-forum
Open in Discord
Avatar
Green KingfisherOP
I am using Server Actions for authentication but the logOutAction not working. The access_token cookie is not getting cleared i can still see it in my brower. How to fix this?

'use server';

import { api } from '@/lib/api';

import { LogInFormType, SignUpFormType } from '@/schemas/auth.schema';
import { cookies } from 'next/headers';

const cookieStore = cookies();

export const signUpAction = async (values: SignUpFormType) => {
try {
const { data } = await api.post('/auth/signup', values);

const { access_token, ...userData } = data.data;

cookieStore.set('access_token', access_token);
return { success: true, message: data.message, data: userData };
} catch (error: any) {
return {
success: false,
message: error.response?.data.message,
errors: error.response?.data.errors,
};
}
};

export const logInAction = async (values: LogInFormType) => {
try {
const { data } = await api.post('/auth/login', values);
const { access_token, ...userData } = data.data;
cookieStore.set('access_token', access_token);

return { success: true, message: data.message, data: userData };
} catch (error: any) {
return {
success: false,
message: error.response?.data.message,
errors: error.response?.data.errors,
};
}
};

export const logOutAction = () => {
cookieStore.delete('access_token');
};
Answered by Julienng
Yup cookies() call are tied to the current request, so you can't call it outside the function, need to be moved inside your functions
View full answer

7 Replies

Avatar
can you try making it async?
Avatar
@chisto can you try making it async?
Avatar
Green KingfisherOP
export const logOutAction = async () => {
cookieStore.delete('access_token');
};

did it still not working
Avatar
Chub mackerel
check the response headers when you invoke this action
does it contain the required set-cookie header?
Avatar
Chub mackerel
oh and also, you should probably do cookies().set(...) or cookies().delete(...) directly instead of const cookieStore = cookies();
Avatar
Yup cookies() call are tied to the current request, so you can't call it outside the function, need to be moved inside your functions
Answer
Avatar
Green KingfisherOP
this worked thanks guys.