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
1import { preValidation, RouteHandler } from "gadget-server";23const route: RouteHandler = async ({ reply }) => {4 await reply.send("this is a protected route!");5};67route.options = {8 preValidation,9};1011export default route;
1import { preValidation, RouteHandler } from "gadget-server";23const route: RouteHandler = async ({ reply }) => {4 await reply.send("this is a protected route!");5};67route.options = {8 preValidation,9};1011export 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
1export const SomePage = () => (2 <BrowserRouter>3 <Routes>4 <Route path="/" element={<Layout />}>5 {/* This route will be accessible only if the user is signed out */}6 <Route7 index8 element={9 <SignedOutOrRedirect>10 <Home />11 </SignedOutOrRedirect>12 }13 />14 {/* This route will be accessible only if the user is signed in */}15 <Route16 path="my-profile"17 element={18 <SignedInOrRedirect>19 <MyProfile />20 </SignedInOrRedirect>21 }22 />23 </Route>24 </Routes>25 </BrowserRouter>26);
1export const SomePage = () => (2 <BrowserRouter>3 <Routes>4 <Route path="/" element={<Layout />}>5 {/* This route will be accessible only if the user is signed out */}6 <Route7 index8 element={9 <SignedOutOrRedirect>10 <Home />11 </SignedOutOrRedirect>12 }13 />14 {/* This route will be accessible only if the user is signed in */}15 <Route16 path="my-profile"17 element={18 <SignedInOrRedirect>19 <MyProfile />20 </SignedInOrRedirect>21 }22 />23 </Route>24 </Routes>25 </BrowserRouter>26);