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.

routes/GET-protected-route.js
JavaScript
1import { preValidation } from "gadget-server";
2
3export default async function route({ reply }) {
4 await reply.send("this is a protected route!");
5}
6
7route.options = {
8 preValidation,
9};
1import { preValidation } from "gadget-server";
2
3export default async function route({ reply }) {
4 await reply.send("this is a protected route!");
5}
6
7route.options = {
8 preValidation,
9};

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
1<BrowserRouter>
2 <Routes>
3 <Route path="/" element={<Layout />}>
4 {/* This route will be accessible only if the user is signed out */}
5 <Route
6 index
7 element={
8 <SignedOutOrRedirect>
9 <Home />
10 </SignedOutOrRedirect>
11 }
12 />
13 {/* This route will be accessible only if the user is signed in */}
14 <Route
15 path="my-profile"
16 element={
17 <SignedInOrRedirect>
18 <MyProfile />
19 </SignedInOrRedirect>
20 }
21 />
22 </Route>
23 </Routes>
24</BrowserRouter>

Was this page helpful?