79146504

Date: 2024-10-31 22:34:18
Score: 1.5
Natty:
Report link

I faced the same problem but found a solution (thanks to this article):

At first, it's important to state we are using this guide and this repository.

  1. Split your server.js into 2 files:

... // imports & constants (without port)

export const app = express();

... // server code

// Start http server
import { app } from './server.js';

const port = process.env.PORT || 5173;

app.listen(port, () => {
  console.log(`Server started at http://localhost:${port}`);
});

Then, change scripts in package.json:

  "scripts": {
    "dev": "node startServer",
    ...
    "preview": "cross-env NODE_ENV=production node startServer"
  }

This will allow you to still start your app locally.

  1. In your project directory, create a directory api and place there a file index.js containing:

import { app } from '../server.js';

export default app;

We did this to let Vercel start our server as a serverless function. Vercel cannot use app.listen().

  1. In your project directory, create a file vercel.json containing:

{
  "version": 2,
  "public": true,
  "rewrites": [
    { "source": "/(.*)", "destination": "/api/index.js" }
  ],
  "functions": {
    "api/index.js": {
      "includeFiles": "dist/client/**"
    }
  }
}

rewrites forwards all requests to a serverless function. includeFiles allows to serve the directory and access files.

  1. Deploy as usual.
Reasons:
  • Blacklisted phrase (0.5): thanks
  • Blacklisted phrase (1): this guide
  • Blacklisted phrase (1): this article
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: Ben Barnes