I've got a svelte Header
component. In this component there's a logout
button. When the button is clicked a function is invoked and this function calls a server side function. In this function I've got a redirect statement that doesn't seem to work.
Here's part of the component (pasting only relevant code):
<script> /** * Logs out the current user. * @returns {Promise<void>} */ const logout = async () => { // call to internal API to perform logout. const response = await fetch("/api/user-logout", { method: "POST", }); }</script><header><!-- Logout --><div class="tooltip tooltip-left" data-tip="Log out"><button on:click={logout} class="relative p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-600 focus:bg-gray-100 focus:text-gray-600 rounded-full"><span class="sr-only">Log out</span><svg aria-hidden="true" class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"/></svg></button></div></header>
Here's api/user-logout/+server.js
:
import { redirect } from "@sveltejs/kit";export async function POST({ request, fetch, cookies, event}) { // remove the auth cookie. // cookies.delete(AUTH_TOKEN_KEY, { path: '/' }); // redirect user to login page. throw redirect(302, '/login');}
The above function is being hit for sure as I added some log statements and they are being printed but the redirect never happens.
I also tried using only redirect(302, '/login')
as I'm using sveltekit 2.5 but didn't work.
I made it work by returning a response from api/user-logout/+server.js
and then using goto
in the frontend function:
const logout = async () => { // call to internal API to perform logout. const response = await fetch("/api/user-logout", { method: "POST", }); if (await response.status == 200) { await goto("/login") } }
It works but I'd rather have the redirect from api/user-logout/+server.js
.
What am I missing?