-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathmiddleware.ts
More file actions
61 lines (59 loc) · 1.96 KB
/
Copy pathmiddleware.ts
File metadata and controls
61 lines (59 loc) · 1.96 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
import { defineMiddleware, HTTPError } from 'h3'
import type { Middleware } from 'h3'
import { createSupabaseContext } from '../../create-supabase-context.js'
import type { SupabaseContext, WithSupabaseConfig } from '../../types.js'
/**
* H3 middleware that creates a {@link SupabaseContext} and stores it in `event.context.supabaseContext`.
*
* Skips if a previous middleware already set the context, enabling chained middleware via `app.use()`.
* Throws an `HTTPError` on auth failure.
*
* @param config - Auth modes and optional environment overrides. CORS is excluded — use H3's CORS utilities.
* @returns An H3 middleware.
*
* @example App-wide auth via app.use()
* ```ts
* import { H3 } from 'h3'
* import { withSupabase } from '@supabase/server/adapters/h3'
*
* const app = new H3()
* app.use(withSupabase({ auth: 'user' }))
*
* app.get('/games', async (event) => {
* const { supabase } = event.context.supabaseContext
* return supabase.from('favorite_games').select()
* })
*
* export default { fetch: app.fetch }
* ```
*
* @example Per-route auth via defineHandler
* ```ts
* import { defineHandler } from 'h3'
* import { withSupabase } from '@supabase/server/adapters/h3'
*
* export default defineHandler({
* middleware: [withSupabase({ auth: 'user' })],
* handler: async (event) => {
* const { supabase } = event.context.supabaseContext
* return supabase.from('favorite_games').select()
* },
* })
* ```
*
* @category Adapters
*/
export function withSupabase(
config?: Omit<WithSupabaseConfig, 'cors'>,
): Middleware {
return defineMiddleware(async (event, next) => {
const context = event.context as { supabaseContext?: SupabaseContext }
if (context.supabaseContext) return next()
const { data: ctx, error } = await createSupabaseContext(event.req, config)
if (error) {
throw new HTTPError(error.message, { status: error.status, cause: error })
}
context.supabaseContext = ctx
return next()
})
}