new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Hono · all subjects

advanced middleware

20 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

@hono/auth-js package React-only support

The @hono/auth-js package currently only supports React for client-side integration.

Install @hono/auth-js with dependencies

To use Auth.js authentication with Hono, install: npm install hono @hono/auth-js @auth/core @auth/drizzle-adapter

Environment variables for Auth.js

Configure these environment variables for Auth.js integration: AUTH_SECRET (authentication secret), GITHUB_ID (GitHub OAuth client ID), GITHUB_SECRET (GitHub OAuth client secret), GOOGLE_ID (Google OAuth client ID), GOOGLE_SECRET (Google OAuth client secret). Generate AUTH_SECRET with: openssl rand -base64 32 or npx auth secret

initAuthConfig middleware setup

Use initAuthConfig middleware to configure Auth.js in Hono. It takes a callback function receiving the Hono context and returns a configuration object with: adapter (DrizzleAdapter or other adapter connecting to database), secret (AUTH_SECRET from environment), providers (array of Auth.js providers like GitHub and Google), session (strategy: 'jwt' for stateless or 'database' for persistent), and callbacks (hooks for sign-in or session events).

verifyAuth middleware

Use verifyAuth() middleware in Hono to verify authentication status on routes. It validates the session and populates c.get('authUser') with authenticated user information.

authHandler middleware for Auth.js routes

Use authHandler() middleware to mount Auth.js routes (typically at /auth/*). It handles OAuth callback, signin, signout, and other authentication endpoints required by Auth.js providers.

DrizzleAdapter with Auth.js in Hono

DrizzleAdapter connects Auth.js to a Drizzle ORM database. Pass it a Drizzle instance and a configuration object specifying: usersTable, accountsTable, authenticatorsTable, sessionsTable, verificationTokensTable. Example: DrizzleAdapter(c.get('db'), { usersTable: users, accountsTable: accounts, authenticatorsTable: authenticators, sessionsTable: sessions, verificationTokensTable: verificationTokens })

Auth.js database schema for SQLite with Drizzle

The Auth.js Drizzle adapter requires these SQLite tables: users table with columns (id: text primaryKey, name: text, email: text unique, emailVerified: integer timestamp_ms, image: text); accounts table with columns (userId: text notNull references users.id, type: text notNull, provider: text notNull, providerAccountId: text notNull, refresh_token: text, access_token: text, expires_at: integer, token_type: text, scope: text, id_token: text, session_state: text) with compound primary key on [provider, providerAccountId]; sessions table with columns (sessionToken: text primaryKey, userId: text notNull references users.id, expires: integer timestamp_ms notNull); verificationTokens table with columns (identifier: text notNull, token: text notNull, expires: integer timestamp_ms notNull) with composite primary key on [identifier, token]; authenticators table with columns (credentialID: text notNull unique, userId: text notNull references users.id, providerAccountId: text notNull, credentialPublicKey: text notNull, counter: integer notNull, credentialDeviceType: text notNull, credentialBackedUp: integer boolean notNull, transports: text) with composite primary key on [userId, credentialID].

Session strategy options in Auth.js

Auth.js supports two session strategies: 'jwt' for stateless sessions stored in JWT tokens, and 'database' for persistent sessions stored in the database.

GitHub and Google providers in Auth.js

Auth.js provides OAuth providers for GitHub and Google. Import GitHub from '@auth/core/providers/github' and Google from '@auth/core/providers/google'. Each provider requires clientId and clientSecret configuration options.

Example: Route protection with Auth.js in Hono

To protect a route, check if the user is authenticated: app.get('/protected', (c) => { const auth = c.get('authUser'); if (!auth) return c.json({ error: 'Unauthorized' }, 401); return c.json(auth); })

React SessionProvider and useSession hook

For React client-side integration with @hono/auth-js, wrap your app with SessionProvider from '@hono/auth-js/react', and use the useSession hook to access session data and sign-in/sign-out functions. Example: const { data: session } = useSession(); call signIn('github') to initiate GitHub OAuth.

Auth.js callbacks configuration

Auth.js supports callbacks to hook into authentication events. The session callback allows custom modification of session data before returning it to the client. Example: callbacks: { async session({ session }) { return session; } }

hono-openapi middleware for automatic OpenAPI documentation

hono-openapi is a middleware that enables automatic OpenAPI documentation generation for Hono APIs by integrating with validation libraries including Zod, Valibot, ArkType, TypeBox, and all libraries supporting Standard Schema.

Install hono-openapi with standard validator

To install hono-openapi, run 'npm install hono-openapi @hono/standard-validator'. To use Valibot specifically, also install 'npm install valibot @valibot/to-json-schema'.

describeRoute function for route documentation in hono-openapi

The describeRoute function is used to add documentation and validation metadata to routes. It accepts an object with properties including 'description' for the route description and 'responses' for defining response schemas. The responses object maps HTTP status codes to objects containing a 'description' and 'content' property, where content maps MIME types to schema definitions using resolver().

validator function in hono-openapi automatically includes OpenAPI request schema

When using the validator() function from hono-openapi, any validation added for 'query', 'json', 'param', or 'form' is automatically included in the OpenAPI request schema. There is no need to manually define request parameters inside describeRoute().

openAPIRouteHandler generates OpenAPI specification endpoint

The openAPIRouteHandler function creates an endpoint that serves the OpenAPI specification document. It accepts the Hono app instance as the first parameter and a configuration object as the second parameter. The configuration object includes a 'documentation' property containing 'info' (with title, version, and description) and 'servers' (array of objects with url and description properties).

resolver function converts validation schemas to OpenAPI schemas

The resolver function is used within describeRoute to convert validation library schemas into OpenAPI-compatible schema format. It is used when defining response content schemas.

Example hono-openapi route with query validation and OpenAPI documentation

import { Hono } from 'hono' import { describeRoute, resolver, validator } from 'hono-openapi' import * as v from 'valibot' const querySchema = v.object({ name: v.optional(v.string()), }) const responseSchema = v.string() const app = new Hono() app.get( '/', describeRoute({ description: 'Say hello to the user', responses: { 200: { description: 'Successful response', content: { 'text/plain': { schema: resolver(responseSchema) }, }, }, }, }), validator('query', querySchema), (c) => { const query = c.req.valid('query') return c.text(`Hello ${query?.name ?? 'Hono'}!`) } ) app.get( '/openapi', openAPIRouteHandler(app, { documentation: { info: { title: 'Hono API', version: '1.0.0', description: 'Greeting API', }, servers: [ { url: 'http://localhost:3000', description: 'Local Server' }, ], }, }) )

Give your agent this brain