Use express.js with nuxt.js

Express.js in one of the most popular Node.js framework, so if you’re working with Nuxt.js and want to use it with express.js because you want user express.js capabilities with nuxt.js, in this quick tutorial we will learn how to use nuxt.js with express.js.

Article Contents

Using Nuxt.js middleware with express.js

Nuxt.js provides nuxt.render middleware to use it with other frameworks such as express.js, along with nuxt.render we will be using loadNuxt, build methods from nuxt.js to achieve this.

use Nuxt.js as a middleware with nuxt.render for your Express.js/node.js server

const express = require("express");
const { loadNuxt, build } = require("nuxt");

const { NODE_ENV } = process.env;

const isDev = NODE_ENV !== "production";
const port = process.env.PORT || 9876;

async function start() {
  const app = express();

  app.get("/api/hello", (req, res) => {
    res.json({ message: "world" });
  });

  // create a next instance
  const nuxt = await loadNuxt(isDev ? "dev" : "start");

  // Render every route with Nuxt.js
  app.use(nuxt.render);

  // Render docs route with Nuxt.js
  app.use("/docs", nuxt.render);

  // Render app route with Nuxt.js
  app.use("/app", 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().catch(console.log);

One thing remember is to call nuxt.render at the end of your middlewares since it will handle the rendering of your web application and won’t call next()


when call api end point /api/hello it will return json response.

// json response from api
{ message: "world" }

In this way you can use nuxt.js with express. So you can use all the prebuilt tools of express.js with nuxt.js. if you have any thoughts, improvements and suggestions please comment below, so that it will help other fellow developers.

See also  Google Recaptcha Node.JS (Express.js) Tutorial

Leave a Comment