diff --git a/server/api/[...req].ts b/server/api/[...req].ts new file mode 100644 index 00000000..88e27d59 --- /dev/null +++ b/server/api/[...req].ts @@ -0,0 +1,44 @@ +import { defineEventHandler, getCookie, getRequestHeaders, getRequestURL, readBody } from 'h3' + +const API_ORIGIN = process.env.API_ORIGIN as string + +export default defineEventHandler(async (event) => { + const { method } = event.node.req + const headers = getRequestHeaders(event) + const url = getRequestURL(event) + const pathname = url.pathname.replace(/^\/api/, '') + + const targetUrl = API_ORIGIN + pathname + (url.search || '') + + const verificationId = headers['verification-id'] as string | undefined + let bearer = '' + if (verificationId) { + bearer = getCookie(event, `Verification-${verificationId}`) || '' + if (!bearer) bearer = getCookie(event, 'authentication') || '' + } else { + bearer = getCookie(event, 'authentication') || '' + } + + const forwardHeaders = new Headers() + if (headers['content-type']) forwardHeaders.set('Content-Type', headers['content-type']) + forwardHeaders.set('Authorization', `Bearer ${bearer}`) + + let body: any = undefined + if (['POST', 'PATCH'].includes(method!)) { + if (headers['content-type']?.includes('multipart/form-data')) { + body = await readBody(event) + } else { + body = await readBody(event) + forwardHeaders.set('Content-Type', 'application/json') + body = JSON.stringify(body) + } + } + + const res = await fetch(targetUrl, { + method, + headers: forwardHeaders, + body, + }) + + return res +})