SpaceNode
SpaceNode provides a declarative auth system. You define your verification logic once, the framework provides the guard.
Call once in your entry point. Applies to all apps:
import { createApp, defineAuth } from 'SpaceNode'
defineAuth(async (token) => {
// token = extracted from "Bearer TOKEN" header
// Return user object if valid, null if invalid
const session = await Session.findOne({ token, active: true })
if (!session) return null
const user = await User.findById(session.userId)
return user
? { id: user.id, name: user.name, role: user.role }
: null
})
const app = await createApp()
Each app instance can have its own auth verifier. Overrides the global defineAuth() for that app. The verifier receives the token and optionally the request context (useful for multi-tenant auth):
const app = await createApp()
app.setAuth(async (token, request) => {
try {
return jwt.verify(token, process.env.JWT_SECRET)
} catch {
return null
}
})
app.listen(3000)
request gives you access to headers, IP, cookies, and more. This is useful for multi-tenant auth where you need request context to determine which tenant's credentials to verify against.auth guard runs, it first checks for a per-app verifier (app.setAuth()). If none is set, it falls back to the global defineAuth() verifier.Once defined, use 'auth' in any route's pipe array:
routes: [
['GET', '/me', 'me', ['auth']],
['POST', '/logout', 'logout', ['auth']],
['GET', '/admin', 'admin', ['auth', 'role:admin']],
]
Authorization: Bearer TOKEN headerapp.setAuth()) or global verifier (defineAuth())null → 401 Unauthorizedrequest.user directlyimport jwt from 'jsonwebtoken'
defineAuth(async (token) => {
try {
const payload = jwt.verify(token, process.env.JWT_SECRET)
return { id: payload.sub, role: payload.role }
} catch {
return null
}
})