CORE CONCEPTS
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.
Api | Description | Where to use |
---|---|---|
useNavigate | Perform a client-side redirection | Event 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. |
The useNavigate
hook is used to perform client-side redirections.
TypeScript
JavaScript
tsximport 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> ) }
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
.
TypeScript
JavaScript
tsximport React from "react"; import { PageComponent, LoaderResponse } 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 (): Promise<LoaderResponse> => { /** * You have the possibility to perform some logic here for example, making API calls * checking if the user is authenticated, etc. */ return { redirect: "/destination" } } export default RedirectionPage;
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.
TypeScript
JavaScript
tsximport 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;
Error Handling
Server-Side Rendering