How to redirect in SvelteKit endpoints
Dana Woodman
Posted on April 21, 2021
UPDATED April 7, 2023
SvelteKit now supports using redirect
to throw redirect(301, '/some-age')
as a convenience.
import { redirect } from '@sveltejs/kit';
export async function GET() {
// Do some magic here... ✨
throw redirect(302, '/success')
}
Thanks Brian in the comments for the reminder about this change 🙏
Wanted to do redirects in your SvelteKit endpoints and tried to return { redirect: '/success' }
just to find out it doesn't work?
Well, you're in luck because you can just use the standard Location
header to do redirects:
export async function GET() {
// Do some magic here... ✨
return {
headers: { Location: '/success' },
status: 302
}
}
Remember to make sure use the proper status code for your redirect.
Learn more about the Location
header on MDN.
Whelp, that's it for today, hope this saved you some headaches!
Follow me on Dev.to, Twitter and Github for more web dev and startup related content
Posted on April 21, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
August 21, 2024