53

I try to get a production build in next.js to run it on my server but I can't build next.js production build when I try

npm run build

Does anyone know how to get a prod build in next.js working correctly I did everything in the next.js documentation but always get this error below. If I do a dev build it works just fine but trying prod build results in errors.

I did also next build many times and reinstalled all node_modules packages still having this error.

it always shows me in terminal

Error: Could not find a valid build in the '/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/.next' directory! Try building your app with 'next build' before starting the server.
    at Server.readBuildId (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/next-server.js:753:15)
    at new Server (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/next-server.js:80:25)
    at module.exports (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/next.js:6:10)
    at Object.<anonymous> (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/next.config.js:6:13)
    at Module._compile (internal/modules/cjs/loader.js:707:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:718:10)
    at Module.load (internal/modules/cjs/loader.js:605:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:544:12)
    at Function.Module._load (internal/modules/cjs/loader.js:536:3)
    at Module.require (internal/modules/cjs/loader.js:643:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at loadConfig (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/config.js:47:28)
    at _callee2$ (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/build/index.js:52:42)
    at tryCatch (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/regenerator-runtime/runtime.js:62:40)
    at Generator.invoke [as _invoke] (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/regenerator-runtime/runtime.js:288:22)
    at Generator.prototype.(anonymous function) [as next] (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/regenerator-runtime/runtime.js:114:21)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `next build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/kk/.npm/_logs/2018-12-10T19_58_00_588Z-debug.log

server.js

const express = require("express");
const next = require("next");

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV === "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  server.get("*", (req, res) => {
    return handle(req, res);
  });

  server.listen(port, err => {
    if (err) throw err;
    console.log(`> Ready on http://localhost:${port}`);
  });
});

next.config.js

const express = require("express");
const next = require("next");

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV === "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  server.get("/projects/:page", (req, res) => {
    const page = req.params.page;
    let file = "";
    switch (page) {
      case "example1":
        file = "/projects/example1";
        break;
      case "example2":
        file = "/projects/example2";
        break;
    }
    return app.render(req, res, file, { page });
  });

  server.get("*", (req, res) => {
    return handle(req, res);
  });

  server.listen(port, err => {
    if (err) throw err;
    console.log(`> Ready on http://localhost:${port}`);
  });
});

package.json

 {
  "name": "hello-next",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "dev": "node server.js",
    "build": "next build",
    "export": "next export"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@zeit/next-sass": "^1.0.1",
    "express": "^4.16.4",
    "next": "^7.0.2",
    "react": "^16.6.3",
    "react-dom": "^16.6.3",
    "redux": "^4.0.1",
    "video-react": "^0.13.1"
  }
}

I plan to run this next.js site using node on my AWS server. But to do this I need to get production build of react.js currently I can run just a development build.

1
  • Add this line in package.json: "start": "cross-env NODE_ENV=production node server.js" Use npm start after npm run build Commented Dec 11, 2018 at 12:34

4 Answers 4

51

next build followed by next start should be the right commands to prepare the build for production and run it.

Here's an example for package.json. if you want to export application to run as a static content, something like hosting it in s3 as a static website, you need to run next export

...
"scripts": {
    "build": "next build",
    "start": "next start",
    "export": "next export"
}
...

Make sure you have the above scripts in your package.json then run the following in order

$ npm run build 
$ npm run start

If you want to start application with specific port, you can specify -p port as argument for npm run command

npm run start -- -p 3232

If you want to incorporate this into a CI/CD pipeline, you need to have Dockerfile, here's a simple example

FROM node:alpine

#copy source 
COPY . /app

# Install deps 
RUN cd /app &&  npm install 

# Build 
RUN npm run build

ENTRYPOINT [ "npm", "run", "start" ]

Still need more explanation or help, don't hesitate to leave a comment and I will be more than happy to assist.

Sign up to request clarification or add additional context in comments.

7 Comments

Why do COPY . /app and cd /app? Use WORKDIR /app and then . in place of the /app directory.
@Muhammad Soliman: I am new to NEXT.JS, could you please let me know what is the reason for 'npm run start'? usually in react we don't execute that command, we directly point build directory to domain.
@TejasPatel npm run start should run the specified script called start in package.json - you could name the script start whatever you want though. in such case it would be npm run <script_name>
@ErikE this was just for clarifying the purpose of commands in a simple way to make it easy for beginner readers to understand.
@MuhammadSoliman Understood, but we also need to teach beginners how to write their Dockerfiles "the Docker way," not write them idiosyncratically. Understanding WORKDIR is so fundamental to Dockerfiles, that giving beginners an answer that doesn't incorporate it is more likely to handicap them than to really help them, unless you give them a BIG hint in your answer, "Do not use this file as-is. You should leverage WORKDIR to write Dockerfiles properly." with a link to the correct docs or a stackoverflow answer on how to use WORKDIR correctly.
|
9

Seems your server.js config is not correct. Please try moving all you have from your next.config.js to server.js make sure the next.config.js file is empty then create a new npm run script:

"prod_start": "NODE_ENV=production node server.js"

Your package.json should then look like this:

{
  "name": "hello-next",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "dev": "node server.js",
    "build": "next build",
    "prod_start": "NODE_ENV=production node server.js",
    "export": "next export"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@zeit/next-sass": "^1.0.1",
    "express": "^4.16.4",
    "next": "^7.0.2",
    "react": "^16.6.3",
    "react-dom": "^16.6.3",
    "redux": "^4.0.1",
    "video-react": "^0.13.1"
  }
}

make sure to run: npm run build && npm run prod_start

Then you should have a production build of react running using next.js

Let me know if you got question.

6 Comments

This is so simple, now it works don't know what to say. Thanks so much! Really appreciated your help.
@Karim, I am using similar setup (express + next.js), can you please tell me how to build and deploy next.js app. When run next build command, it generates .next folder. I am not getting if I need to move all my app source (server.js etc.) to production server and run npm start, as my express.js server files are not moving/bundling to .next folder.
@RakeshRawat did u found out the solution to your problem, I am having the same doubts :(
Why node server.js and not next start ?
pm2 start npm --name "next-app" -- start this also help
|
1

You must launch next build at your root folder and not inside .next/

Comments

-1

There are 3 ways todo it:-

way 1: use next build instead of npm run build

way 2: npm run build npm install -g serve serve -s build more info: https://create-react-app.dev/docs/deployment/

way 3: after npm run build, Remove / from JS,CSS links from /static/index.html file. eg. replace these 2 lines

<script defer="defer" src="/static/js/main.aa87bc08.js"></script>
<link href="/static/css/main.073c9b0a.css" rel="stylesheet"/>

with these 2 lines

<script defer="defer" src="static/js/main.aa87bc08.js"></script>
<link href="static/css/main.073c9b0a.css" rel="stylesheet" />

now it even work on file:///D:/codes/ProjectName/build/index.html

tell me in the comments if none of the 3 ways work, I'll find, try & tell way 4, 5, etc.

1 Comment

next build is the same thing as npm run build according to his package.json...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.