-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathmiddleware.ts
More file actions
74 lines (70 loc) · 2.29 KB
/
Copy pathmiddleware.ts
File metadata and controls
74 lines (70 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import type { MiddlewareHandler } from 'hono'
import { createMiddleware } from 'hono/factory'
import { HTTPException } from 'hono/http-exception'
import { createSupabaseContext } from '../../create-supabase-context.js'
import type { SupabaseContext, WithSupabaseConfig } from '../../types.js'
/**
* Hono middleware that creates a {@link SupabaseContext} and stores it in `c.var.supabaseContext`.
*
* Skips if a previous middleware already set the context, enabling route-level overrides.
* Throws a Hono `HTTPException` on auth failure.
*
* @param config - Auth modes and optional environment overrides. CORS is excluded — use Hono's `cors()`.
* @returns A Hono middleware that sets `c.var.supabaseContext`.
*
* @example App-wide auth via app.use()
* ```ts
* import { Hono } from 'hono'
* import { withSupabase } from '@supabase/server/adapters/hono'
* import type { SupabaseContext } from '@supabase/server'
*
* type Env = {
* Variables: {
* supabaseContext: SupabaseContext
* }
* }
*
* const app = new Hono<Env>()
* app.use('*', withSupabase({ auth: 'user' }))
*
* app.get('/profile', async (c) => {
* const { supabase } = c.var.supabaseContext
* const { data } = await supabase.rpc('get_profile')
* return c.json(data)
* })
*
* export default { fetch: app.fetch }
* ```
*
* @category Adapters
*/
export function withSupabase<Database = unknown>(
config?: Omit<WithSupabaseConfig, 'cors'>,
): MiddlewareHandler<{
Variables: { supabaseContext: SupabaseContext<Database> }
}> {
return createMiddleware<{
Variables: { supabaseContext: SupabaseContext<Database> }
}>(async (c, next) => {
// Skip if a previous middleware already set the context.
// This enables route-level overrides: a route can use withSupabase({ auth: 'secret' })
// while the app-wide middleware uses withSupabase({ auth: 'user' }), without the
// app-wide one overwriting the stricter context already established.
if (c.var.supabaseContext) {
await next()
return
}
const { data: ctx, error } = await createSupabaseContext<Database>(
c.req.raw,
config,
)
if (error) {
throw new HTTPException(error.status as 401 | 500, {
message: error.message,
cause: error,
})
}
c.set('supabaseContext', ctx)
await next()
})
}