diff --git a/src/server.ts b/src/server.ts index c4efb0d..8671380 100644 --- a/src/server.ts +++ b/src/server.ts @@ -12,6 +12,24 @@ import { getIdFilters } from '@welshman/util' export const server: express.Application = express() +// The browser hits /subscription with an Authorization header and Content-Type: +// application/json, which triggers a CORS preflight. Answer it and allow the +// configured origin so the client can register. +const corsOrigin = process.env.CORS_ORIGIN ?? '*' + +server.use((req: Request, res: Response, next: NextFunction) => { + res.setHeader('Access-Control-Allow-Origin', corsOrigin) + res.setHeader('Access-Control-Allow-Methods', 'GET,POST,DELETE,OPTIONS') + res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization') + res.setHeader('Access-Control-Max-Age', '86400') + + if (req.method === 'OPTIONS') { + return res.sendStatus(204) + } + + next() +}) + server.use(express.json()) server.use(express.static('web/dist'))