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.
- Gatekeeping: When a user attempts to access any route under
/dashboard/*, the middleware checks for the presence of theauth-tokencookie. - Redirection: If the cookie is missing, the user is instantly redirected to
/login, with anextquery parameter preserving their original destination (e.g.,/login?next=/dashboard). - Session Block: Logged-in users who try to visit
/loginare 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
- The user enters credentials in
LoginForm.tsx. - A
POSTrequest is sent to the N-Keys identity provider:https://secrets.nekonik.com/user/login. - Upon success, two things are extracted:
- User Payload: The JSON body containing the user's
id,name,email, andpermissions. - CSRF Token: Extracted from the
x-csrf-tokenHTTP header.
- User Payload: The JSON body containing the user's
- These values are saved into Jotai's persistent store (
atomWithStorage), syncing them directly into the browser'slocalStorageso 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.