Protecting Routes
Secure your application using JopiJS's declarative security system. Learn how to lock folders and specific actions without code.
Security in JopiJS is visual. You secure a folder by simply creating an empty file inside it. No complex middleware or configuration required.
Prerequisites:
- Project initialized with
minimaltemplate (see here for instructions). - Ensure your server is running (
npm run start:dev_server).
1. Creating the Admin Module
In JopiJS, security rules are defined within your modules. Let's create a dedicated module for our protected area.
- Go to
src/. - Create a folder named
mod_admin. - Inside, create a folder named
@routes.
2. Protecting a Folder (Total Lockdown)
We want to create a /dashboard area accessible only to users with the admin role.
Step 1: Create the route
Inside src/mod_admin/@routes, create a folder named dashboard.
Add a simple page.tsx file:
export default function AdminDashboard() {
return <h1 className="p-10 text-2xl">Welcome to the Secure Dashboard</h1>;
}Step 2: Add the lock
Inside the dashboard folder, create a new empty file named:
needRole_admin.cond
Step 3: Verify
- Open
http://localhost:3000/dashboard. - JopiJS will detect the
.condfile and block access because you are not logged in as an admin. - You will see a 401 Unauthorized error.
3. Granular Protection
Sometimes you want a page to be public, but restrict certain actions (like posting a message).
Step 1: Create a public page with a private action
Let's create a /contact route in mod_admin/@routes/.
- Create folder
contact. - Add a
page.tsx(the form) and anonPOST.ts(the handler).
Step 2: Protect only the POST method
Inside the contact folder, create this empty file:
postNeedRole_validated.cond
Now:
- GET
/contact(Viewing the page) -> Allowed for everyone. - POST
/contact(Submitting the form) -> Blocked unless the user has thevalidatedrole.
4. Security Rules Summary
| File Prefix | Scope |
|---|---|
needRole_ | Everything (Folder + all subfolders) |
pageNeedRole_ | Page Only (page.tsx) |
postNeedRole_ | POST API Only (onPOST.ts) |
getNeedRole_ | GET API Only |
Important Concepts:
- Inheritance: If you protect a folder, every file and sub-folder inside it is automatically protected.
- Logical OR: If you place
needRole_admin.condANDneedRole_editor.condin the same folder, users can access it if they are an Admin OR an Editor.