Docs
Core Concepts
Routing
Redirecting

Redirecting

There are a few ways you can handle redirects in Rasengan.js. This page will go through each available option, use cases, and how to manage large numbers of redirects.

ApiDescriptionWhere to use
useNavigatePerform a client-side redirectionEvent Handlers in Client Components
PageComponent.loader()Enable redirection on the server.During the server-side rendering process.
LayoutComponent.loader()Enable redirection on the server.During the server-side rendering process.

useNavigate hook

The useNavigate hook is used to perform client-side redirections.

src/components/LogoutButton.tsx
import React from "react";
import { useNavigate } from "rasengan";
 
export default function LogoutButton() {
  const navigate = useNavigate();
 
  const logout = async () => {
    try {
      // Logout logic Here
 
      navigate("/sign-in");
    } catch (error) {
      console.error(error);
    }
  }
 
  return (
    <button onClick={logout}>Logout</button>
  )
}

The useNavigate hook is used in event handlers in client components to perform client-side redirections. After the logout logic is executed, the navigate function is called with the path to redirect to.

PageComponent.loader() function

Similar to LayoutComponent.loader(), the PageComponent.loader() function is a special function used for SSR (Server-Side Rendering) like getServerSideProps in Next.js.

So, you can perform server-side redirections using this function and it can only be used in Page Components.

The loader function is not only used for redirections, but it can also be used to perform server-side operations like making API calls, checking if the user is authenticated, etc. and it can pass data to the PageComponent as props. Read more about it here.

The loader function can receive an object argument containing:

  • a request instance: The request object from the server.
  • a param object: The parameters from the URL.
src/app/redirection.page.tsx
import React from "react";
import { PageComponent, LoaderResponse, LoaderOptions } from "rasengan";
 
const RedirectionPage: PageComponent = () => {
  return (
    <div>
      <h1>Redirecting...</h1>
    </div>
  )
}
 
RedirectionPage.path = "/somewhere";
RedirectionPage.metadata = {
  title: "Redirect",
  description: "Redirecting to somewhere",
}
 
// Used to perform server-side operations
RedirectionPage.loader = async ({ params, request }: LoaderOptions): Promise<LoaderResponse> {
  /**
    * You have the possibility to perform some logic here for example, making API calls
    * checking if the user is authenticated, etc.
    *
    * You can also access the request object from the server and the params object
    */
 
  return {
    redirect: "/destination"
  }
}
 
export default RedirectionPage;

Next Steps

Project Organization
Dynamic Routes
Logo Image