JBaczuk
JBaczuk

Reputation: 14629

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.

Upvotes: 4

Views: 6436

Answers (1)

JBaczuk
JBaczuk

Reputation: 14629

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",
    ...
}

Upvotes: 10

Related Questions