-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite.config.js
More file actions
129 lines (116 loc) · 4.28 KB
/
Copy pathvite.config.js
File metadata and controls
129 lines (116 loc) · 4.28 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
import dotenv from 'dotenv'
// Load environment variables
dotenv.config()
export default defineConfig({
plugins: [
react(),
{
name: 'vercel-api-routes',
configureServer(server) {
server.middlewares.use('/api', async (req, res, next) => {
try {
// Parse cookies manually
const cookies = {}
if (req.headers.cookie) {
req.headers.cookie.split(';').forEach(cookie => {
const parts = cookie.trim().split('=')
if (parts.length === 2) {
cookies[parts[0]] = decodeURIComponent(parts[1])
}
})
}
// Parse request body for POST/PUT requests
let body = {}
if (req.method === 'POST' || req.method === 'PUT') {
const chunks = []
for await (const chunk of req) {
chunks.push(chunk)
}
const rawBody = Buffer.concat(chunks).toString()
try {
if (req.headers['content-type']?.includes('application/json')) {
body = JSON.parse(rawBody)
} else if (req.headers['content-type']?.includes('application/x-www-form-urlencoded')) {
body = Object.fromEntries(new URLSearchParams(rawBody))
}
} catch (e) {
console.warn('Failed to parse request body:', e)
}
}
// Parse query parameters
const url = new URL(req.url, `http://${req.headers.host}`)
const query = Object.fromEntries(url.searchParams)
// Get the API route path
const apiPath = url.pathname.replace('/api', '')
// Dynamically import the API handler with environment variables
const modulePath = path.resolve(process.cwd(), `api${apiPath}.js`)
// Make sure environment variables are available in the API context
process.env.KV_REST_API_URL = process.env.KV_REST_API_URL
process.env.KV_REST_API_TOKEN = process.env.KV_REST_API_TOKEN
const { default: handler } = await import(modulePath + '?t=' + Date.now())
// Create mock request object
const mockReq = {
method: req.method,
query,
body,
headers: req.headers,
cookies,
url: req.url
}
// Create mock response object
const mockRes = {
statusCode: 200,
headers: {},
status(code) {
this.statusCode = code
return this
},
json(data) {
res.statusCode = this.statusCode
Object.entries(this.headers).forEach(([key, value]) => {
res.setHeader(key, value)
})
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify(data))
return this
},
setHeader(name, value) {
this.headers[name] = value
return this
},
end(data = '') {
res.statusCode = this.statusCode
Object.entries(this.headers).forEach(([key, value]) => {
res.setHeader(key, value)
})
res.end(data)
return this
}
}
// Call the handler
await handler(mockReq, mockRes)
} catch (error) {
console.error('API Route Error:', error)
res.statusCode = 500
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({
error: 'Internal Server Error',
details: error.message
}))
}
})
}
}
],
server: {
port: 5177
},
define: {
global: 'globalThis',
},
// Make sure Vite loads environment variables
envPrefix: ['VITE_', 'KV_', 'ADMIN_', 'VERCEL_', 'GITHUB_', 'EMAIL_', 'RESEND_', 'CLOUDINARY_', 'OPENAI_']
})