Hi I’m trying to implement the logout logic, my session token is stored in the cookies, which I want to clear if the token is no longer valid. But next.js is not allowing me to do so, even so their documentation says that I can update cookies from a server action. I feel most likely the way I’m invoking server actions is the issue, if so, can u help with the better way.
This is a little confusing to me, all comments are welcomed.
import React from 'react';
import { gql } from '@urql/core';
import { cookies } from 'next/headers';
import { getClient } from '../actions';
import { redirect } from 'next/navigation';
const PokemonsQuery = gql`
query Me {
me {
id
username
roles
createdAt
updatedAt
}
}
`;
export default async function Home() {
const result = await getClient().query(PokemonsQuery, {}).toPromise();
async function logout() {
'use server'
// remove cookie
cookies().delete('access_token');
// redirect to login page
redirect('/login');
}
// if any issue happens then logout
if(result.error && result.error.networkError){
await logout();
}
return (
<main>
<h1>This is rendered as part of an RSC</h1>
<ul>
<div>
<p>id: {result.data.me.id}</p>
<p>username: {result.data.me.username}</p>
<p>roles: {result.data.me.roles.join(', ')}</p>
<p>createdAt: {result.data.me.createdAt}</p>
<p>updatedAt: {result.data.me.updatedAt}</p>
</div>
</ul>
</main>
);
}
error:
Error: Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options
at $$ACTION_0 (./src/app/server/page.tsx:125:67)
at Home (./src/app/server/page.tsx:41:15)
2
Answers
It seems like you are trying to do a cookie write operation inside a
Server Component
and not aServer Action
. Though, you can read the cookies inside aServer Compononent
, you can’t write it. So, you can update your code to be:-page.tsx
actions.ts
There are scenarios where you can use server actions, but not anywhere in your code, Read more.
Just create a route handler
/api/access_token/route.ts
:And then call it inside your logout function: