I have a serverless logout function in Next.js:
import magic from './magic';
import { withSessionRoute } from './sessions';
export default withSessionRoute(async function logoutHandler(
request,
response,
) {
try {
if (request.method === 'GET') {
if (request.session.user) {
await magic.users.logoutByIssuer(request.session.user.issuer);
}
request.session.destroy();
return response.redirect(302, '/').end();
}
const message = 'This endpoint only supports the GET method.';
return response.status(405).json({ message });
} catch (error) {
console.log(error);
}
});
The key point is
response.redirect(302, '/').end();
.
I trigger this using a button's onClick
handler:
const logoutRoute = '/api/logout';
const logoutRequest = () => axios.get(logoutRoute);
async function handleLogoutClick() {
return await logoutRequest();
}
// ... later
<button onClick={handleLogoutClick}>
{t('user-authentication:logout')}
</button>
However, after the request is resolved, the browser does not redirect to /
.
$ yarn dev
yarn run v1.22.17
$ next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info - Loaded env from /Users/janhesters/dev/my-proj/.env.local
event - compiled client and server successfully in 943 ms (217 modules)
wait - compiling /home (client and server)...
event - compiled client and server successfully in 173 ms (594 modules)
wait - compiling /api/logout...
event - compiled client and server successfully in 96 ms (612 modules)
wait - compiling / (client and server)...
event - compiled client and server successfully in 56 ms (620 modules)
wait - compiling...
event - compiled successfully in 76 ms (58 modules)
https://i.sstatic.net/4KttP.png
What do I need to add so that the frontend actually redirects to /
?