UNPKG

@platform/react.ssr

Version:

A lightweight SSR (server-side-rendering) system for react apps bundled with ParcelJS and hosted on S3.

52 lines (51 loc) 1.82 kB
import { parse as parseUrl } from 'url'; import { fs } from './common'; const CACHE = { 'Cache-Control': `s-maxage=5, stale-while-revalidate` }; export function init(args) { const { router, getManifest } = args; router.get('*', async (req) => { const manifest = await getManifest(); if (!manifest.ok) { const status = manifest.status; const message = 'Manifest could not be loaded.'; return { status, data: { status, message } }; } const host = req.headers.host; const hostname = (host || '').split(':')[0]; const site = manifest.site.byHost(hostname); if (!site) { const status = 404; const message = `A site definition for the domain '${hostname}' does not exist in the manifest.`; return { status, data: { status, message } }; } const url = parseUrl(req.url || '', false); const route = site.route(url.pathname || ''); const ext = fs.extname(url.pathname || ''); if (route && !ext) { const entry = await route.entry(); if (entry.ok) { return { headers: CACHE, data: entry.html, }; } else { const { status, url } = entry; const message = `Failed to get entry HTML from CDN.`; return { status, headers: CACHE, data: { status, message, url }, }; } } const location = site.redirectUrl(url.pathname || ''); if (location) { return { status: 307, data: location, }; } return undefined; }); }