JWT Session
A JWT session encodes/decodes any sessions created during the authentication flow.
This is not a default because it depends on jose
(opens in a new tab).
When to Use
The JWT plugin is useful when you want to store session information -- represented as a JSON object -- with JWT encoding so it cannot be read by the client.
It depends on a third-party package to handle JWT encoding/decoding.
How to Use
- Initialize an instance of the plugin.
// src/session.ts
import { JwtSessionPlugin } from '@aponia.js/core/plugins/session/jwt'
export const session = new JwtSessionPlugin()
With an auth instance.
// src/auth.ts
import { Auth } from '@aponia.js/core'
import { session } from './session'
export const auth = new Auth({
plugins: [session]
})
Headless (express.js)
This example shows how a session can be retrieved, validated, and set on the Request
object on every request in express.js.
It also demonstrates how a session can be created and set as a cookie.
// src/routes.ts
import express from 'express'
import cookieParser from 'cookie-parser'
import { session } from './session'
const app = express()
// On every request, define `req.session` if there's a valid session found in the cookies.
app.use(async (req) => {
const cookieSession = await session.getSession(req.cookies)
const isValid = cookieSession.expires > Date.now()
if (isValid) {
req.session = cookieSession
}
})
// After logging in successfully, create a session cookie.
app.post('/auth/login', async (req, res) => {
// Create new session.
const newSession = {
id: "1"
}
// Create aponia.js cookie object.
const sessionCookie = await session.createCookiesFromSession(newSession)
// Set cookie using express.js API.
res.cookie(sessionCookie.name, sessionCookie.value, sessionCookie.options)
})