Astro JS - Redirecting Routes



What is Redirecting?

Redirecting is a mechanism in web applications, in which user is forcefully made to change the URL of the page that they try to access. This is useful when you want direct your readers to a new page, because your site structure has changed or in response to an action such as logging in to an authenticated route.

How to Setup Redirects in Astro?

In Astro, you can specify the rules for redirects in the 'astro.config.mjs' file. The 'redirects' property in the config file is an array of objects that define the redirect rules. Each object in the array has the following properties:

  • source: The source URL pattern to match. This can be a string or a regular expression.
  • destination: The destination URL to redirect to. This can be a string or a function that returns a string.

Example

In the code below, we define a redirect rule for the '/old-page' URL to the '/new-page' URL.

// File: /astro.config.mjs

import { defineConfig } from 'astro/config';

export default defineConfig({
  redirects: {
    '/old-page': '/new-page',
    '/blog': 'https://example.com/blog'
  }
});

Setup Dynamic Redirects

In dynamic redirects, you can check some special conditions before making the redirect. For example, you can check if the user is logged in or not. If the user is not logged in, you can redirect them to the login page.

Example

In the code below, we check if the user is logged in or not. If the user is not logged in, we redirect them to the login page.

---
    import { isLoggedIn } from '../utils';

    const cookie = Astro.request.headers.get('cookie');

    // If the user is not logged in, redirect them to the login page
    if (!isLoggedIn(cookie)) {
        return Astro.redirect('/login');
    }
---
<html>
    <!-- Page here... -->
</html>

Route Priority Order

Astro uses a route priority order to determine which route to match first. The order is as follows:

  • First priority is for Astro reserved routes, for example, _astro/, _server_islands/ and _actions.
  • Routes with more path segments will take precedence over dynamic routes. For example all routes under /posts/ take precedence over /[...slug].astro at the root.
  • Static routes without path parameters will take precedence over dynamic routes. E.g. /posts/create.astro takes precedence over all the other routes in the example.
  • Dynamic routes using named parameters take precedence over rest parameters. E.g. /posts/[page].astro takes precedence over /posts/[...slug].astro.
  • Pre-rendered dynamic routes take precedence over server dynamic routes.
  • Endpoints take precedence over pages.
  • File-based routes take precedence over redirects.
  • If none of the rules above decide the order, routes are sorted alphabetically based on the default locale of your Node installation.
Advertisements