Workflows 

Protecting HTTP routes 

Your app's HTTP routes can be protected using the preValidation function you can restrict access to signed-in users only.

api/routes/GET-protected-route.js
JavaScript
import { preValidation, RouteHandler } from "gadget-server"; const route: RouteHandler = async ({ reply }) => { await reply.send("this is a protected route!"); }; route.options = { preValidation, }; export default route;
import { preValidation, RouteHandler } from "gadget-server"; const route: RouteHandler = async ({ reply }) => { await reply.send("this is a protected route!"); }; route.options = { preValidation, }; export default route;

This route will return 403 Forbidden if accessed without signing in, and will run the route handler if accessed by someone who is signed in.

Protecting pages (frontend routes) 

Routes in your app's frontend can be protected using two Gadget helper components, SignedInOrRedirect and SignedOutOrRedirect. These components conditionally render their children based on the user's sign-in status and handle redirection to secure frontend routes. Both components use the window.location.assign method to redirect the browser when necessary.

Let's take a look at an example below using both in tandem:

React
export const SomePage = () => ( <BrowserRouter> <Routes> <Route path="/" element={<Layout />}> {/* This route will be accessible only if the user is signed out */} <Route index element={ <SignedOutOrRedirect> <Home /> </SignedOutOrRedirect> } /> {/* This route will be accessible only if the user is signed in */} <Route path="my-profile" element={ <SignedInOrRedirect> <MyProfile /> </SignedInOrRedirect> } /> </Route> </Routes> </BrowserRouter> );
export const SomePage = () => ( <BrowserRouter> <Routes> <Route path="/" element={<Layout />}> {/* This route will be accessible only if the user is signed out */} <Route index element={ <SignedOutOrRedirect> <Home /> </SignedOutOrRedirect> } /> {/* This route will be accessible only if the user is signed in */} <Route path="my-profile" element={ <SignedInOrRedirect> <MyProfile /> </SignedInOrRedirect> } /> </Route> </Routes> </BrowserRouter> );

Was this page helpful?