silphius/server.js

84 lines
2.3 KiB
JavaScript
Raw Normal View History

2024-06-10 19:35:19 -05:00
import {createRequestHandler} from '@remix-run/express';
import compression from 'compression';
import express from 'express';
import morgan from 'morgan';
const isProduction = process.env.NODE_ENV === 'production';
const app = express();
let server;
if (isProduction) {
const {createServer} = await import('node:http');
server = createServer(app);
}
else {
const {execSync} = await import('node:child_process');
const {mkdirSync, readFileSync, statSync} = await import('node:fs');
const cacheDirectory = `${import.meta.dirname}/node_modules/.cache`;
mkdirSync(cacheDirectory, {recursive: true});
try {
statSync(`${cacheDirectory}/localhost-key.pem`);
}
catch (error) { // eslint-disable-line no-unused-vars
execSync(`mkcert -cert-file ${cacheDirectory}/localhost.pem -key-file ${cacheDirectory}/localhost-key.pem localhost`)
}
const serverOptions = {
key: readFileSync(`${cacheDirectory}/localhost-key.pem`),
cert: readFileSync(`${cacheDirectory}/localhost.pem`),
};
const {createServer} = await import('node:https');
server = createServer(serverOptions, app);
}
const viteDevServer = isProduction
? undefined
: await import('vite').then((vite) =>
vite.createServer({
server: {middlewareMode: {server}},
})
);
2024-06-12 23:17:24 -05:00
const ssr = await (
viteDevServer
? viteDevServer.ssrLoadModule('virtual:remix/server-build')
: import('./build/server/index.js')
);
2024-06-10 19:35:19 -05:00
const remixHandler = createRequestHandler({
2024-06-12 23:17:24 -05:00
build: () => ssr,
2024-06-10 19:35:19 -05:00
});
2024-06-12 23:56:50 -05:00
await ssr.entry.module.websocket(server, viteDevServer);
2024-06-10 22:42:30 -05:00
2024-06-10 19:35:19 -05:00
app.use(compression());
// http://expressjs.com/en/advanced/best-practice-security.html#at-a-minimum-disable-x-powered-by-header
app.disable('x-powered-by');
// handle asset requests
if (viteDevServer) {
app.use(viteDevServer.middlewares);
}
else {
// Vite fingerprints its assets so we can cache forever.
app.use(
'/assets',
express.static('build/client/assets', { immutable: true, maxAge: '1y' })
);
}
// Everything else (like favicon.ico) is cached for an hour. You may want to be
// more aggressive with this caching.
app.use(express.static('build/client', { maxAge: '1h' }));
app.use(morgan('tiny'));
// handle SSR requests
app.all('*', remixHandler);
const port = process.env.PORT || 3000;
server.listen(port, () =>
console.log(`Express server listening at http${isProduction ? '' : 's'}://localhost:${port}`)
);