1 import compression from "compression"
2 import { IRouter, Request, Response, Router, static as static_ } from "express"
3 import fs from "fs"
4 import { ServerResponse } from "http"
5 import path from "path"
6
7 type ServeOptions = {
8 outDir: string
9 }
10
11 const router = Router()
12
13 export async function serve(options: ServeOptions): Promise<IRouter> {
14 const htmlPath = path.resolve(options.outDir, "index.html")
15
16 /**
17 * The admin UI should always be built at this point, but in the
18 * rare case that another plugin terminated a previous startup, the admin
19 * may not have been built correctly. Here we check if the admin UI
20 * build files exist, and if not, we throw an error, providing the
21 * user with instructions on how to fix their build.
22 */
23
24 const indexExists = fs.existsSync(htmlPath)
25
26 if (!indexExists) {
27 throw new Error(
28 `Could not find index.html in the admin build directory. Make sure to run 'medusa build' before starting the server.`
29 )
30 }
31
32 const html = fs.readFileSync(htmlPath, "utf-8")
33
34 const sendHtml = (_req: Request, res: Response) => {
35 res.setHeader("Cache-Control", "no-cache")
36 res.setHeader("Vary", "Origin, Cache-Control")
37 res.send(html)
38 }
39
40 const setStaticHeaders = (res: ServerResponse) => {
41 res.setHeader("Cache-Control", "max-age=31536000, immutable")
42 res.setHeader("Vary", "Origin, Cache-Control")
43 }
44
45 router.use(compression() as any)
46
47 router.get("/", sendHtml)
48 router.use(
49 static_(options.outDir, {
50 setHeaders: setStaticHeaders,
51 })
52 )
53 router.get(`/*`, sendHtml)
54
55 return router
56 }