I am using Next-Auth v4.22.1 and NextJS 13.
I am trying to sign out a user inside the [...nextauth].js jwt callback.
I know that signOut() is only available on the client side. If it is used on the server-side we will get a "ReferenceError: window is not defined" error.
My POST request to /api/auth/signout is not working.
I am getting the error
nextauth-signout-requests.js - Fetch Error SyntaxError: Unexpected token E in JSON at position 0
API handler should not return a value, received object.
API resolved without sending a response for /api/nextauth-signout-requests, this may result in stalled requests.
My POST code from nextauth-signout-requests.js :
const NextAuthSignOutReq = async (req, res) => {
if (req.method === 'POST') {
try {
// Sign out the user
const signOut = await fetch(`${HOMEPAGE_URL}/api/auth/signout?callbackUrl=${HOMEPAGE_URL}/api/auth/session`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: await fetch(`${HOMEPAGE_URL}/api/auth/csrf`).then(rs => rs.text())
});
const data = await signOut.json();
if (signOut.status === 200) {
// Success
console.log('User Signed Out');
return res.status(200);
} else {
// Fail
console.log(`nextauth-signout-requests.js - POST to /auth/signout failed`);
return res.status(500);
}
} catch(err) {
// Fail
console.log('nextauth-signout-requests.js - Fetch Error ' + err);
return res.status(500);
}
}
else {
// Error. Not a POST request. They tried GET or PUT etc.
res.setHeader('Allow', ['POST']);
return res.status(405).json({ 'error': `Method ${req.method} not allowed`});
}
}
export default NextAuthSignOutReq;
Anyone know what I am doing wrong? It's almost as if HTML is beign returned not JSON? I think that is what "Unexpected token E in JSON at position 0" means.
I' also not 100% on the CSRF token useage here? Never seen in a NextJS sevrer side POST req before.
Any help is appreciated!