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

Was this page helpful?