Skip to content

Instantly share code, notes, and snippets.

@ThimoDEV
Created July 12, 2025 07:33
Show Gist options
  • Save ThimoDEV/0667f405f93dd6e498cd506a3ff5d1c7 to your computer and use it in GitHub Desktop.
Save ThimoDEV/0667f405f93dd6e498cd506a3ff5d1c7 to your computer and use it in GitHub Desktop.
H3 V2 Beta with orpc example
import { RPCHandler } from '@orpc/server/fetch'
import { H3, handleCors, isPreflightRequest, serve } from 'h3'
import { appRouter } from '@/api/root'
import { ENV } from '@/envCheck'
import { auth } from '@/lib/auth'
import { createContext } from '@/lib/context'
import type { H3Event } from 'h3'
import 'dotenv/config'
const app = new H3()
// #region: Middleware
app.use('*', async (event, next) => {
const session = await auth.api.getSession({ headers: event.req.headers })
if (!session) {
event.context.user = null
event.context.session = null
await next()
}
event.context.user = session?.user ?? null
event.context.session = session?.session ?? null
await next()
})
app.use('/**', async (event) => {
const corsRes = handleCors(event, {
origin: ['http://localhost:3000'],
preflight: {
statusCode: 204,
},
methods: '*',
})
if (corsRes === false || corsRes === '') {
if (isPreflightRequest(event)) {
return new Response(null, {
status: 200,
headers: {
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Origin': 'http://localhost:3000',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Max-Age': '3600',
},
})
}
}
})
// #endregion: Middleware
// #region: RPC
const handler = new RPCHandler(appRouter)
app.use('/rpc/**', async (event, next) => {
const context = await createContext(event)
const { matched, response } = await handler.handle(event.req, {
prefix: '/rpc',
context,
})
if (matched) {
response.headers.set('Access-Control-Allow-Credentials', 'true')
return response
}
await next()
})
// #endregion: RPC
// #region: Base Routes
app.get('/ping', () => {
return 'pong!!!'
})
app
.on('POST', '/api/auth/**', (event) => auth.handler(event.req))
.on('GET', '/api/auth/**', (event) => auth.handler(event.req))
// #endregion Base Routes
serve(app, {
port: ENV.PORT,
})
// Below is in another file
export async function createContext(event: H3Event) {
const session = await auth.api.getSession({
headers: event.req.headers,
})
return {
session,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment