Svelte: Redirect to new page ID
Suppose
- that your website has page IDs in the sense of
domain.com/PAGEID/slug
. For example, you're probably seeing this very page at the addressedstrom.dev/csbxq/redirect-to-new-page-ids-in-sveltekit
, so the ID iscsbxq
. - that you update the ID to use new algorithm, so now it's going to be
6uXpfOI2c9fJdh2aa22
. Time to set up a redirect!
I'll assume your page's loader (the file you've got on a path like src/routes/[id]/[[slug]]/+page.js
) contains this:
import { error } from '$sveltejs/kit' import posts from '$lib/posts.json' export function load({ params }) { let post = posts[params.id] if (post) return post error(404, "Not found") }
Edit that to something like this.
import { error, redirect } from '$sveltejs/kit' import posts from '$lib/posts.json' import v1_to_v2 from '$lib/v1_to_v2.json' // assumed a table of old and new ID export function load({ params }) { let post = posts[params.id] if (post) return post // Redirect from v1 to v2 id let idv2 = v1_to_v2[params.id] if (idv2) redirect(308, `/${idv2}`) error(404, "Not found") }
This assumes that navigating to just domain.com/IDV2
is satisfactory.
To also include the slug in the redirection (remember the slug in domain.com/PAGEID/slug
?), I'll assume your post
object contains metadata post.id
and post.slug
and then we can do the redirection like this:
// ... export function load({ params }) { let post = posts[params.id] if (post) return post // Redirect from v1 to v2 id post = posts[v1_to_v2[params.id]] if (post) redirect(308, `/${post.id}/${post.slug}`) error(404, "Not found") }
Created (8 months ago)