Skip to main content

Authentication

N-Keys uses a hybrid approach to authentication, ensuring both bulletproof security on the server and a snappy, responsive state on the client.

Server-Side: Middleware

Next.js Middleware (middleware.ts) runs at the Edge before any request completes.

  1. Gatekeeping: When a user attempts to access any route under /dashboard/*, the middleware checks for the presence of the auth-token cookie.
  2. Redirection: If the cookie is missing, the user is instantly redirected to /login, with a next query parameter preserving their original destination (e.g., /login?next=/dashboard).
  3. Session Block: Logged-in users who try to visit /login are automatically redirected back into the dashboard.

Client-Side: Jotai

While cookies are great for middleware, modern React apps need complex client-side state for the user interface. We use Jotai for atomic state management.

The Live API Flow

  1. The user enters credentials in LoginForm.tsx.
  2. A POST request is sent to the N-Keys identity provider: https://secrets.nekonik.com/user/login.
  3. Upon success, two things are extracted:
    • User Payload: The JSON body containing the user's id, name, email, and permissions.
    • CSRF Token: Extracted from the x-csrf-token HTTP header.
  4. These values are saved into Jotai's persistent store (atomWithStorage), syncing them directly into the browser's localStorage so they survive page reloads.

Dynamic Rendering

The (dashboard)/layout.tsx reads directly from the userAtom in Jotai to dynamically render the user's Name and Email in the bottom-left corner of the sidebar!

Logout

Clicking logout triggers a confirmation modal. Once confirmed, it deletes the auth-token cookie, wipes the localStorage state via Jotai, and hard-refreshes the Next.js router.