feat(auth-js): Support async ConfigHandler (#1324)

* feat(auth-js): Support async ConfigHandler

* add changeset

* format
pull/1325/head
James Talmage 2025-07-21 01:55:46 -04:00 committed by GitHub
parent b24925168a
commit d89fed7eec
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 28 additions and 2 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/auth-js': minor
---
Allow async authjs Config

View File

@ -47,6 +47,27 @@ describe('Config', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
}) })
it('Should allow async ConfigHandler', async () => {
globalThis.process.env = { AUTH_SECRET: 'secret' }
const app = new Hono()
app.use(
'/*',
initAuthConfig(async () => {
await new Promise((resolve) => setTimeout(resolve, 1))
return {
basePath: '/api/auth',
providers: [],
}
})
)
app.use('/api/auth/*', authHandler())
const req = new Request('http://localhost/api/auth/signin')
const res = await app.request(req)
expect(res.status).toBe(200)
})
it('Should return 401 is if auth cookie is invalid or missing', async () => { it('Should return 401 is if auth cookie is invalid or missing', async () => {
const app = new Hono() const app = new Hono()

View File

@ -29,7 +29,7 @@ export type AuthUser = {
export interface AuthConfig extends Omit<AuthConfigCore, 'raw'> {} export interface AuthConfig extends Omit<AuthConfigCore, 'raw'> {}
export type ConfigHandler = (c: Context) => AuthConfig export type ConfigHandler = (c: Context) => AuthConfig | Promise<AuthConfig>
export function setEnvDefaults(env: AuthEnv, config: AuthConfig): void { export function setEnvDefaults(env: AuthEnv, config: AuthConfig): void {
config.secret ??= env.AUTH_SECRET config.secret ??= env.AUTH_SECRET
@ -118,7 +118,7 @@ export function verifyAuth(): MiddlewareHandler {
export function initAuthConfig(cb: ConfigHandler): MiddlewareHandler { export function initAuthConfig(cb: ConfigHandler): MiddlewareHandler {
return async (c, next) => { return async (c, next) => {
const config = cb(c) const config = await cb(c)
c.set('authConfig', config) c.set('authConfig', config)
await next() await next()
} }