-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathserver.js
64 lines (57 loc) · 1.68 KB
/
server.js
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
import express from "express";
import fs from "fs";
import { createServer as createViteServer } from "vite";
import "dotenv/config";
const app = express();
const port = process.env.PORT || 3000;
const apiKey = process.env.OPENAI_API_KEY;
// Configure Vite middleware for React client
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "custom",
});
app.use(vite.middlewares);
// API route for token generation
app.get("/token", async (req, res) => {
try {
const response = await fetch(
"https://api.openai.com/v1/realtime/sessions",
{
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "gpt-4o-realtime-preview-2024-12-17",
voice: "verse",
}),
},
);
const data = await response.json();
res.json(data);
} catch (error) {
console.error("Token generation error:", error);
res.status(500).json({ error: "Failed to generate token" });
}
});
// Render the React client
app.use("*", async (req, res, next) => {
const url = req.originalUrl;
try {
const template = await vite.transformIndexHtml(
url,
fs.readFileSync("./client/index.html", "utf-8"),
);
const { render } = await vite.ssrLoadModule("./client/entry-server.jsx");
const appHtml = await render(url);
const html = template.replace(`<!--ssr-outlet-->`, appHtml?.html);
res.status(200).set({ "Content-Type": "text/html" }).end(html);
} catch (e) {
vite.ssrFixStacktrace(e);
next(e);
}
});
app.listen(port, () => {
console.log(`Express server running on *:${port}`);
});