Skip to content

Unable to serve static files with Vite + SSR #325

@stychu

Description

@stychu

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.3.0

Plugin version

6.4.1

Node.js version

14.18.1

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

BigSur 11.6.6

Description

Seems like fastify-static doesn't serve files when I try to make PROD build with Vite + SSR.
Incorporating sirv does work but when I switch to fastify-static I get

{
  "message": "Route GET:/ not found",
  "error": "Not Found",
  "statusCode": 404
}

Steps to Reproduce

  1. npm init vite-plugin-ssr --skip-git
  2. pick any name
  3. pick react-ts
  4. replace package.json with
  "scripts": {
    "dev": "npm run server",
    "prod": "npm run build && npm run server:prod",
    "build": "vite build",
    "server": "ts-node ./server",
    "server:prod": "cross-env NODE_ENV=production ts-node ./server"
  },
  "dependencies": {
    "@fastify/static": "6.4.1",
    "@types/node": "18.6.1",
    "@types/react": "18.0.15",
    "@types/react-dom": "18.0.6",
    "@vitejs/plugin-react": "2.0.0",
    "cross-env": "7.0.3",
    "fastify": "4.3.0",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "sirv": "2.0.2",
    "ts-node": "10.9.1",
    "typescript": "4.7.4",
    "vite": "3.0.3",
    "vite-plugin-ssr": "0.4.12"
  },
  "devDependencies": {
    "pino-pretty": "8.1.0"
  }
}
  1. replace ./server/index.ts with
import { createServer as createViteServer } from 'vite';
import { renderPage } from 'vite-plugin-ssr';
import path from 'path';
import fastifyStatic from '@fastify/static';
import sirv from 'sirv';

const isProduction = process.env.NODE_ENV === 'production';
const root = path.resolve();
const assets = sirv(`${root}/dist/client`, {
  immutable: true,
  dev: !isProduction
});

async function startServer () {
  const app = fastify({
    logger: {
      transport:
        !isProduction
          ? {
            target: 'pino-pretty',
            options: {
              translateTime: 'HH:MM:ss Z',
              ignore: 'pid,hostname'
            }
          }
          : undefined
    },
  });

  try {
    if (isProduction) {
      await app.register(fastifyStatic, { root: `${root}/dist/client` });
      // app.addHook('onRequest', (req, reply, done) => {assets(req.raw, reply.raw, done);});
    } else {
      const viteDevMiddleware = await createViteServer({
        root,
        server: {
          middlewareMode: true,
        },
      });

      app.addHook('onRequest', (req, reply, done) => {
        viteDevMiddleware.middlewares(req.raw, reply.raw, done);
      });
    }

    app.get('*', async (req, reply) => {
      const pageContextInit = { url: req.url };
      const pageContext = await renderPage(pageContextInit);
      const { httpResponse } = pageContext;

      if (!httpResponse) return;

      const { body, statusCode, contentType } = httpResponse;

      reply.status(statusCode).type(contentType).send(body);
    });

    const port = (process.env.PORT || 3000) as number;

    await app.listen({ port });

    console.log(`Server running at http://localhost:${port}`);
  } catch (error) {
    app.log.fatal(error);
  }
}

startServer();
  1. npm run prod
  2. visit http://localhost:3000/
  3. See 404
  4. go back to ./server/idex.ts and comment line 33 (await app.register(fastifyStatic, { root: ${root}/dist/client });) and uncomment line 34 (app.addHook('onRequest', (req, reply, done) => {assets(req.raw, reply.raw, done);});)
  5. restart process and visit http://localhost:3000/
  6. You can see application

Expected Behavior

I should be able to see application when using fastify-static

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions