Nuxt with Express
Having issues in getting started with Nuxt and Express? Never mind, let's get started.
Step 1: Install nuxt
npm init nuxt-app mynuxtapp
Step 2: Start nuxt
npm run dev
We are just checking whether everything has got installed correctly or not. 100% this should start nuxt app at port 3000.
Step 3: Server
Create a folder named ‘server’ in the root, Add a file onto it and name it index.js. Go to https://nuxtjs.org/api/nuxt-render/ and copy the code from there and paste it to index.js file.
Step 4: package.json
Modify the dev script in package.json file as
"scripts": {
"dev": "cross-env NODE_ENV=development nodemon server/index.js --watch server",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate",
"lint:js": "eslint --ext .js,.vue --ignore-path .gitignore .",
"lint": "npm run lint:js"
},
Step 5: Start the server
npm run dev
This will throw an error saying that cross-env is not installed, and also if there any other package that is not installed. Install the packages using `npm i <package-name>` command, and start the server again. Now your app is has an express backend.
Step 6: Adding backend api routes
Create two folders inside `server` and name it `model` and `routes`. And all your models and routes to respective folders. Next, import the routes inside the nuxt render function.
const { loadNuxt, build } = require("nuxt");
const app = require("express")();const isDev = process.env.NODE_ENV !== "production";
const port = process.env.PORT || 3000;
require('custom-env').env()async function start() { /* BODY PARSER */
/***************************************/
const bodyParser = require("body-parser"); // for parsing application/xwww-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies // for parsing application/json
app.use(bodyParser.json());
/***************************************/ const mongoose = require("mongoose");
mongoose.connect(process.env.MONGODB_URL, {
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true
}); /*THIS PART*/
const userRouter = require("./routes/user");
app.use("/api/user", userRouter);
/*THIS PART*/ // We get Nuxt instance
const nuxt = await loadNuxt(isDev ? "dev" : "start"); // Render every route with Nuxt.js
app.use(nuxt.render); // Build only in dev mode with hot-reloading
if (isDev) {
build(nuxt);
} // Listen the server
app.listen(port, "0.0.0.0");
console.log("Server listening on `localhost:" + port + "`.");
}start();
In the above example, I have added body-parser, which is an essential part of all API's, I have added mongoose because I use MongoDB as my database on most of my projects. If you are not using mongoose then skip that code. The only thing that you need is that code inside /*THIS PART*/ comment. Now all the requests that hit api/user will be served by the router and everything else will be handled by the nuxt renderer. Cool right… Start building.