Redirects

Sometimes you want to redirect a user from the current page to another page.

Let's say a user tries to go to a dashboard page but has not logged in yet. We want them to be redirected to a login page so they can be authenticated.

src/routes/dashboard.tsx
import type { RequestEvent } from '@builder.io/qwik-city';
import { checkAuthorization } from '../auth'; // Your authorization code
import type { DashboardData } from '../types'; // Your types
 
export const onGet = async ({ cookie, redirect }: RequestEvent) => {
  const isAuthorized = checkAuthorization(cookie.get('cookie'));
 
  if (!isAuthorized) {
    // User is not authorized!
    // throw the redirect response to
    // relocate the user to the log-in page
    throw redirect(302, '/login');
  } else {
    // ...
  }
};

The redirect() function, which was destructured in the RequestHandler function arguments, takes a redirect status code and URL.

throw redirect(302, '/login');

Common redirect status codes:

  • 301: Moved Permanently. This and all future requests should be directed to the given URI.
  • 302: Found. This response code means that the URI of requested resource has been changed temporarily. Further changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests.
  • 307: Temporary Redirect. The server sends this response to direct the client to get the requested resource at another URI with the same method that was used in the prior request. This has the same semantics as the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.
  • 308: Permanent Redirect. This means that the resource is now permanently located at another URI, specified by the Location HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.

If you do not provide a status code, Qwik City will default to a 302 Found status.

Read more about redirect status codes here.

Contributors

Thanks to all the contributors who have helped make this documentation better!

  • adamdbradley
  • manucorporat
  • mhevery
  • mrhoodz
  • hamatoyogi