Couldn't find a `pages` directory. NextJS with pkg

Viewed 1426

I want to make a NextJS executable app for Windows, but I get this annoying error:

(node:18500) UnhandledPromiseRejectionWarning: Error: > Couldn't find a pages directory. Please create one under the project root

I have a pages folder in the root folder

Below is server.js

const { createServer } = require('http')
const next = require('next')

const port = parseInt(process.env.PORT, 10) || 3003
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev, dir: __dirname })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  createServer((req, res) => {
    const parsedUrl = new URL(req.url, 'http://w.w')
    const { pathname, query } = parsedUrl

    if (pathname === '/a') {
      app.render(req, res, '/a', query)
    } else if (pathname === '/b') {
      app.render(req, res, '/b', query)
    } else {
      handle(req, res, parsedUrl)
    }
  }).listen(port, (err) => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})

And package.json

{
  "name": "custom-server",
  "version": "1.0.0",
  "scripts": {
    "dev": "node server.js",
    "build": "next build",
    "start": "cross-env NODE_ENV=production node server.js",
    "pkg": "pkg . --targets node12-win-x64 --out-path pkg"
  },
  "dependencies": {
    "cross-env": "^7.0.2",
    "next": "latest",
    "pkg": "^4.4.9",
    "react": "^17.0.1",
    "react-dom": "^17.0.1"
  },
  "main": "server.js",
  "license": "MIT",
  "bin": "server.js",
  "pkg": {
    "assets": [
      ".next/**/*"
    ],
    "scripts": [
      ".next/server/**/*.js"
    ]
  }
}

How can I solve this issue and make a NextJS working executable ?

1 Answers

When you run the build make sure you set NODE_ENV to production, also pass a conf to your server.js as per the docs.

const app = next({ dev, dir: __dirname, conf : {output : "standalone"} })

NODE_ENV should be production for all your tasks besides run dev.

Related