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.
server.js
into 2 files:server.js
... // 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.
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()
.
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.