Adding Nuxt to an existing Express service
Well, usually you do completely the opposite. But maybe there is another developer that is looking for this tutorial, as I was.
Why?
Before moving further, I would like to explain why I needed it. If you already have your own reasons then just skip this part.
At my company we have a PaaS team that maintains a service for creating internal services (yeah tautology…). Why so? It reduces a significant amount of time when creating a new service. You get a fully configured Express template on GitHub with already enabled CI/CD and all the internal dependency packages within a few minutes. So it was more natural to add Nuxt to an already existing Express service, rather than using create-nuxt-app
and configuring serverMiddleware
from scratch.
How?
Let’s start by creating our app. Open terminal and choose a folder to work in.
mkdir nuxt-as-express-middleware; cd nuxt-as-express-middleware
Initializing the app.
npm init
Installing dependencies.
npm i express nuxt
Creating the heart of the app.
touch app.js
Open app.js in your favorite editor and copy-paste this code.
Well, that’s it. But if you’re interested in what is going on here let’s dig a bit deeper.
loadNuxt
first searches for nuxt.config.js if it doesn’t exist Nuxt uses default configurations. After loading the configurations it creates and returns an instance of Nuxt.
nuxt.render
is a classical middleware function which maps Express requests to Nuxt routes. Because this function will handle the rendering of your web application and won’t call next()
you should call it at the end of your middlewares.
build
this name is pretty self describable. Here Nuxt prepares the project for development, builds it and serves the files (by default from .nuxt directory).
TL;DR
I want to mention that I’m not a Nuxt developer and not professional in it. I used documentation and debug tools for exploring how things work under the hood, so please feel free to correct me if I’m anywhere wrong.