Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build next.js app with custom server for production in Typescript

I have a custom express server I use to create an api and to host the static content generated by next.js. When I try to build for production, it says:

Error: Could not find a production build in the 'path/to/project/.next' directory. Try building your app with 'next build' before starting the production server.

like image 581
JBaczuk Avatar asked Nov 16 '25 04:11

JBaczuk


1 Answers

The next.js project and the custom server must be built separately.

  1. Delete any .next and dist folders
  2. In the project root, create an additional tsconfig file called tsconfig.server.json which extends the main tsconfig.json configuration. Assuming the custom server is in a folder ./server and the developer wants the output directory to be called ./dist.
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "commonjs",
    "outDir": "dist",
    "target": "es2017",
    "isolatedModules": false,
    "noEmit": false
  },
  "include": ["server"]
}
  1. Edit scripts in package.json
"scripts": {
    "build:server": "tsc --project tsconfig.server.json",
    "build:next": "next build",
    "build": "npm run build:next && npm run build:server",
    "start:prod": "NODE_ENV=production node dist/server/index.js",
    ...
}
like image 166
JBaczuk Avatar answered Nov 17 '25 20:11

JBaczuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!