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:


1. Creating the Admin Module

In JopiJS, security rules are defined within your modules. Let's create a dedicated module for our protected area.

  1. Go to src/.
  2. Create a folder named mod_admin.
  3. 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

  1. Open http://localhost:3000/dashboard.
  2. JopiJS will detect the .cond file and block access because you are not logged in as an admin.
  3. 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/.

  1. Create folder contact.
  2. Add a page.tsx (the form) and an onPOST.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 the validated role.

4. Security Rules Summary

File PrefixScope
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.cond AND needRole_editor.cond in the same folder, users can access it if they are an Admin OR an Editor.