@proteles/next
v0.1.1
Published
Next.js bindings for the Proteles Backend-for-Frontend: catch-all /api/auth/* route handlers, authMiddleware, and next/headers server helpers over @proteles/bff. Tokens never reach the browser.
Maintainers
Readme
@proteles/next
A Backend-for-Frontend (BFF) that adds Proteles authentication to a Next.js app.
Why a BFF? Access and refresh tokens live only inside an encrypted,
httpOnly cookie set by your own server. The browser never receives a token —
it only ever sees the sanitized user object from /api/auth/me. This sidesteps
the "refresh token in localStorage" footgun and is how modern Auth0/Clerk SDKs
work.
It ports the reference webapp/session.go + webapp/handlers.go (encrypted
session/flow cookies, PKCE redirect flow, transparent refresh-with-rotation,
revoke-on-logout) to Next.js, built on @proteles/js.
Install
npm install @proteles/next @proteles/jsSetup (three files)
// app/api/auth/[...proteles]/route.ts
import { createAuthHandlers } from "@proteles/next";
export const { GET, POST } = createAuthHandlers();// middleware.ts — protect everything except public routes
export { authMiddleware as middleware } from "@proteles/next";
export const config = { matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"] };// any Server Component / route / action
import { currentUser } from "@proteles/next";
const user = await currentUser(); // { sub, email, preferredUsername } | nullPrefer the @proteles/react components (<SignInButton>,
<UserButton>, useUser()) for the client UI — they talk to these route
handlers, never to the authorization server directly.
Configuration (environment)
All read from the environment; nothing is required in code.
| Variable | Required | Default | Notes |
| --- | --- | --- | --- |
| PROTELES_ISSUER | ✅ | | Your tenant's issuer, e.g. https://acme.proteles.com |
| PROTELES_CLIENT_ID | ✅ | | |
| PROTELES_CLIENT_SECRET | | | Set for a confidential client (recommended for a BFF) |
| PROTELES_REDIRECT_URI | ✅* | | * or derive from PROTELES_APP_URL + /api/auth/callback |
| PROTELES_APP_URL | | | App origin, used to derive the redirect URI |
| PROTELES_SESSION_SECRET | ✅ | | Base64 of 32 random bytes — encrypts the cookies |
| PROTELES_SCOPES | | openid profile email offline_access | |
| PROTELES_COOKIE_SECURE | | true | Set false only for plain-HTTP local dev |
| PROTELES_POST_LOGIN_REDIRECT | | / | |
| PROTELES_BASE_PATH | | /api/auth | Where the route handlers are mounted |
Generate a session secret:
node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"You can also pass any of these to createAuthHandlers({ ... }) /
createAuthMiddleware({ ... }) explicitly instead of using env.
Endpoints
The catch-all route handles, relative to basePath (/api/auth):
| Route | What it does |
| --- | --- |
| GET /login?returnTo=…&connection=… | Starts login: sets the flow cookie, redirects to the AS (PKCE + state + nonce). connection picks a social provider. |
| GET /callback | Verifies state, exchanges the code, fetches userinfo, sets the session cookie, redirects to returnTo. |
| GET|POST /logout?returnTo=… | Revokes the refresh token (best-effort), clears the session. |
| GET /me | { authenticated, user? } — transparently refreshes an expired access token first. |
| GET /revalidate?returnTo=… | Refreshes a spent-but-refreshable session, sets the rotated cookie, and redirects back to returnTo (or to the login flow if the session is gone). authMiddleware sends users here by default, because middleware cannot attach a cookie to a "continue" response — without the bounce an expired access token would send people to log in every 15 minutes. Opt out with authMiddleware({ revalidate: false }). |
Security notes
- The session cookie is AES-256-GCM encrypted (Web Crypto, so it also works on the Edge runtime where middleware runs); a tampered or wrong-key value is rejected and never trusted.
stateis validated with a constant-time comparison; a mismatch fails closed.returnTois restricted to same-origin absolute paths — no open redirects.- Failed logins redirect to
…?proteles_error=login_failedwith a generic signal; the raw AS error is never surfaced to the browser.
Develop
npm install # from the sdk/ workspace root
npm run build # tsc -> dist
npm test # tsx + node:test (full login→callback→me→logout flow, mocked AS)