Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build next.js production?

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

If anyone has an idea would be so nice! 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.

Hope someone has an idea.

Thanks in advance!

like image 515
Cody Avatar asked Dec 10 '18 20:12

Cody


People also ask

Is NextJS good for production?

Faster time to market – NextJS is a great way of creating MVP as fast as possible thanks to many premade components. This way of building allows you to get feedback quickly and improve your product accordingly without wasting both time and money.

Who uses next JS in production?

Next. js is widely used by the biggest and most popular companies all over the world like Netflix, Uber, Starbucks, or Twitch. It's also considered as one of the fastest-growing React frameworks, perfect to work with static sites – which was the hottest topic in the web development world lately.

How does next JS build work?

When you build your application, Next. js will transform your code into production-optimized files ready to be deployed to servers and consumed by users. These files include: HTML files for statically generated pages.


2 Answers

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.

like image 148
Muhammad Soliman Avatar answered Sep 22 '22 21:09

Muhammad Soliman


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.

like image 29
Karim Avatar answered Sep 22 '22 21:09

Karim