-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.ts
More file actions
67 lines (55 loc) · 1.53 KB
/
Copy pathserver.ts
File metadata and controls
67 lines (55 loc) · 1.53 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
import '~/config/compress.config'
import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { logger } from 'hono/logger'
import { compress } from 'hono/compress'
//
import { Users } from '~/routes'
import { auth, initDB } from '~/config'
import { errorHandler, notFound } from '~/middlewares'
// Initialize the Hono app with base path
const app = new Hono<{
Variables: {
user: typeof auth.$Infer.Session.user | null
session: typeof auth.$Infer.Session.session | null
}
}>({ strict: false })
// Initialize and check the database connection
initDB()
// Determine the environment
const port = process.env?.PORT || 8000
const API_BASE = process.env.API_BASE || '/api/v1'
// Logger middleware
app.use(logger())
// Compress middleware
app.use(compress({ encoding: 'gzip' }))
// CORS configuration (tightened for security)
app.use(
'*',
cors({
origin: ['http://localhost:3000', 'http://localhost:8000'], // Specify allowed origins (update for production)
credentials: true,
maxAge: 86400, // Cache preflight for 1 day
})
)
// Home Route
app.get('/', c => {
return c.json({
message: 'Welcome to the Hono API',
})
})
// Better-Auth - Handle all auth routes
app.on(['POST', 'GET'], '/api/auth/*', c => {
return auth.handler(c.req.raw)
})
// Users Route
app.route(API_BASE + '/users', Users)
// Error Handler (improved to use err)
app.onError(errorHandler)
// Not Found Handler (standardized response)
app.notFound(notFound)
// Export for both Bun and Cloudflare Workers
export default {
port,
fetch: app.fetch,
}