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.

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

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:

jsx
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>