I am trying to optimize SSR performance of my React.JS. The code is running on AWS Fargate. Migrated it from ExpressJS to Fastify to try to speed things-up. Hit a bunch of issues. Resolved most of them. Now, visually, it is working. Locally, everything is working.
The actual Fastify server is pretty simple, as below:
const main = async () => {
process.on('unhandledRejection', err => {
console.error(err);
process.exit(1);
});
const server = fastify({ logger: true });
server.register(shutdown);
server.register(compress);
server.register(require('fastify-static'), {
root: path.join(__dirname, '../build/static'),
prefix: '/static',
decorateReply: false
});
server.register(require('fastify-static'), {
root: path.join(__dirname, '../build/icons'),
prefix: '/icons',
decorateReply: false
});
server.get('/*', fp(loader));
server.head('/*', fp(loader));
const PORT = process.env.PORT || 3000;
const address = await server.listen(PORT, '0.0.0.0');
server.log.info(`Server running at: ${address}`);
server.gracefulShutdown((signal, next) => {
next();
});
module.exports = server;
};
The actual logic is in the loader or the bootstrap code.
Locally, everything is working fine. No errors.
{
"level": 30,
"time": 1630430883204,
"pid": 1,
"hostname": "07f3ccb2c7a84af983e545c1b1a2924c-45249757",
"reqId": "req-56",
"req": {
"method": "GET",
"url": "/static/js/7.48a37794.chunk.js",
"hostname": "storefront.warmonger.com",
"remoteAddress": "10.64.33.5",
"remotePort": 4174
},
"msg": "incoming request"
}
When I run it inside AWS Fargate, I get a bunch of errors in the log caused by fastify-static, I believe. They are all the same - something like the below:
{
"level": 50,
"time": 1630436845304,
"pid": 1,
"hostname": "07f3ccb2c7a84af983e545c1b1a2924c-45249757",
"reqId": "req-8e",
"stack": "Error: premature close\n at onclosenexttick (/ssr/node_modules/end-of-stream/index.js:54:86)\n at processTicksAndRejections (internal/process/task_queues.js:79:11)",
"type": "Error",
"msg": "premature close"
}
Some requests for static files succeed, and many fail. Only files handled by fastify-static have problems. I am running fastify-static 4.2.3. Google Lighthouse cannot render any pages.
What could I do?