Next.js [JavaScript]


Next.js is a framework for server-render or statically-exported React apps. In this article, I would like to introduce basic knowledge for Next.js.

🎃 Install

cd /project/path/to/

# Install next and some libraries
yarn add next react react-dom

🎂 Server Side Support for Clean URLs

Please add Express.js:

yarn add express

Then create a file server.js in your app and add following content:

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

const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

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

// Support clean URLs
server.get("/p/:id", (req, res) => {
const actualPage = "/post";
const queryParams = { id: req.params.id };
app.render(req, res, actualPage, queryParams);
});

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

server.listen(3000, err => {
if (err) throw err;
console.log("> Ready on http://0.0.0.0:3000");
});
})
.catch(ex => {
console.error(ex.stack);
process.exit(1);
});

In addtion, please add pages/post.js and write following code:

export default props => <h1>post page id: {props.url.query.id} in next.jsh1>;

After modifying, please update package.json:

{
"scripts": {
"dev": "node server.js"
}
}

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!