Guides
Authentication
How the backend knows who is calling, and how routes become public or private.
Authentication is how the backend knows who sends a request. In newt it is one function, the authenticator in src/auth.ts: it reads the request and returns the user, or null.
The authenticator
Section titled “The authenticator”newt init writes src/auth.ts:
import type { Authenticator } from '@newt-js/core/http'
export const authenticate: Authenticator = async () => nullIts type, from @newt-js/core/http:
type Authenticator = (request: HttpRequest) => Promise<Actor | null>
interface Actor { userId: string}- Return
{ userId }when the request comes from someone you recognise. - Return
nullwhen it does not. requestis aRequestwithrequest.cookies(aBun.CookieMap) andrequest.params.
The generated one returns null, so every private route answers 401 until you write it.
Where it is used
Section titled “Where it is used”Each context gives it to its router, in its <context>.context.ts:
const router = new HttpRouter({ prefix: '/tasks/api', database })router.authenticateWith(authenticate)Every context imports the same authenticate, so one function covers the whole backend. A context may call authenticateWith with a different one.
Private and public routes
Section titled “Private and public routes”This is what the router does with each request before your route runs:
Every route is private by default. Before a private route runs, the router calls the authenticator:
- It returns
{ userId }: the route runs, with that user as the actor. - It returns
null, or there is no authenticator: the route does not run, and the answer is a 401.
{"error":"Sign in first","code":"not_signed_in"}Mark a route public to skip the authenticator:
router.post('/sign-in', signIn, { public: true })public works wherever route options go:
| Where | Applies to |
|---|---|
router.get(path, route, { public: true }) |
one route |
router.group(prefix, { public: true }) |
every route of the group |
new HttpRouter({ public: true }) |
every route of the router |
- A public route has no actor.
currentActor()throws there;findCurrentActor()returnsundefined. - A public route cannot be idempotent: the router throws when you register one with
idempotency.
Who may go on
Section titled “Who may go on”Signing in says who calls, not what they may enter. To close a path, and all that hangs from it, to those who may not enter (a workspace to whoever is not in it), give the context’s router a guard: see Guards.
Bearer tokens
Section titled “Bearer tokens”bearerAuthenticator reads the Authorization: Bearer <token> header and hands the token to your function:
import { bearerAuthenticator } from '@newt-js/core/http'// --------------------------------------------------------import { verifyToken } from './verify-token'
export const authenticate = bearerAuthenticator(async token => { const userId = await verifyToken(token) return userId ? { userId } : null})verifyTokenis yours: it checks the token and returns the user’s id, ornull.- Without the header, or with another scheme, it returns
nullwithout calling your function. - The word
Beareris matched in any case.
Session cookies
Section titled “Session cookies”A session cookie suits a frontend served by the same backend. Two helpers write it:
setSessionCookie(request, name, value, { secure, maxAgeSeconds, path, domain })clearSessionCookie(request, name, { secure, path, domain })| Option | Meaning | Default |
|---|---|---|
secure |
send it over HTTPS only | required |
maxAgeSeconds |
how long it lasts | required |
path |
where the browser sends it | / |
domain |
a domain whose subdomains get it too, such as midominio.com |
only the host that set it |
- The cookie is always
HttpOnlyandSameSite=Lax. clearSessionCookiewrites an empty cookie with a max age of 0.- Both set the cookie on
request.cookies. The router adds it to the response for you.
A sign-in route sets the cookie, and the authenticator reads it:
import type { Authenticator } from '@newt-js/core/http'// --------------------------------------------------------import { userOfSession } from './user-of-session'
export const SESSION_COOKIE = 'session'
export const authenticate: Authenticator = async request => { const session = request.cookies.get(SESSION_COOKIE) const userId = session ? await userOfSession(session) : null return userId ? { userId } : null}import { bodyOf } from '@newt-js/core/http'import { setSessionCookie } from '@newt-js/core/http'
router.post( '/sign-in', async request => { const session = await signIn(await bodyOf(request)) setSessionCookie(request, SESSION_COOKIE, session, { secure: Bun.env.NODE_ENV === 'production', maxAgeSeconds: 60 * 60 * 24 * 30, }) return new Response(null, { status: 204 }) }, { public: true },)userOfSession and signIn stand for your own code: how you check a password or a session is up to you.
One sign-in for every context’s host
Section titled “One sign-in for every context’s host”When contexts answer at their own hosts, such as backoffice.midominio.com and hr.midominio.com, a cookie set without domain goes only to the host that set it: moving from one to the other signs the user out. Give the cookie the shared domain, and every subdomain gets it:
setSessionCookie(request, SESSION_COOKIE, session, { secure: true, maxAgeSeconds: 60 * 60 * 24 * 30, domain: Bun.env.SESSION_DOMAIN,})- Clear it with the same
domain, or the browser keeps it. - The cookie says who the user is, everywhere. What each one may do is still each context’s to decide, in its use cases: being signed in to
backofficedoes not openhr. - Every subdomain of that domain gets the cookie, so give it only a domain whose subdomains are all yours.
The actor in your code
Section titled “The actor in your code”While a private route runs, the user the authenticator returned is the current actor. It stays the actor through every await and every use case the route calls.
| Function | Returns |
|---|---|
currentActor() |
the actor, or throws NoActor (401) |
findCurrentActor() |
the actor, or undefined |
runAsActor(actor, fn) |
runs fn as that actor |
All three come from @newt-js/core.
- The actor’s
userIdis saved with every event the request emits. - Rate limits count by actor by default, and by IP when there is none.
- Idempotency keys are kept per actor.
See actor and scope.
Errors
Section titled “Errors”| Error | Status | code |
When |
|---|---|---|---|
NotSignedIn |
401 | not_signed_in |
a private route, nobody signed in |
NoActor |
401 | not_signed_in |
currentActor() with no actor |
CrossOriginRefused |
403 | cross_origin_refused |
a write from another origin |
In tests
Section titled “In tests”The generated module tests give the router an authenticator of their own, which they switch off to check the 401:
router = new HttpRouter({ prefix: '/tasks/api', database })signedIn = truerouter.authenticateWith(async () => signedIn ? { userId: 'tester' } : null)So the tests pass whatever src/auth.ts does. See testing.