Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To make the redirect() function in SvelteKit work on the server while still keeping the ssr (server-side rendering) enabled, you can use the following approach:

  1. Import the goto function from the SvelteKit router library in your server code:
import { goto } from '@sveltejs/kit/kit';
  1. Instead of calling redirect() directly in your server-side function, use the goto function to navigate to the desired URL:
export async function get({ params }) {
  // some code to determine the redirect URL
  const redirectUrl = '/new-page';

  // use goto() to navigate to the new page
  return goto(redirectUrl);
}
  1. Make sure to return the result of the goto function in your server response to signal to SvelteKit that the redirect navigation should be performed.

When the goto function is called on the server, it generates a special response with a 302 redirect status code and the Location header set to the specified URL. When this response is received by the browser, it will trigger a client-side navigation to the new URL. This approach allows you to perform server-side redirects while still retaining the benefits of SvelteKit's server-side rendering.