Using NuxtJS Server Middleware as a Proxy Pass

NuxtJS is an amazing tool for building SSR applications with Vue. There are so many benefits right out of the box such as PWA support, automatic routing, plugins, and modules. One really powerful feature, which is less documented, is server middleware.

Middleware

By default, middleware in NuxtJS is also exposed to the client side. This is useful for common middleware like auth where you need to ensure that a token is set in the local storage or cookie for a user to ensure they are authenticated. However, there are cases where you might want to mask 

Server Middleware

NuxtJS describes server middleware as "a connect instance that we can add our own custom middleware to. This allows us to register additional routes (typically /api routes) without need for an external server." So what exactly does that mean? 

With NuxtJS as your framework, you gain server and client support automatically. There are many instances where you may have environment variables that you want to only render on the server side and not expose to the client this could be an internal API, key, or etc. NuxtJS allows this through the use of server middleware. 

Use Case

Image the following scenario, we have an internal API to users of the NuxtJS application will consume, but we do not want to expose the API to the users directly. In this scenario, we can create a server middleware that will handle requests and proxy pass them to a server defined by the environment variable.

First, let's create a new folder to store the server middleware. NuxtJS uses /api in their example, but this folder name is completely up to you (although I would avoid placing it in /middleware/server just from an organization standpoint). Keeping with the NuxtJS documentation, create api/v1/index.js

Note: don't forget to npm or yarn require the http-proxy package.

With the server middleware created, we need to register it with the nuxt.config.js. 

Now anytime to hit /api/v1 our requests will be proxy passed to the API defined by the environment in the server middleware!

Note: it's important that you do not define the environment using the nuxt.config.js env property as this will publish the values to the server and client.

Resources

A lot of credit goes to this video by Program with Erik (https://www.programwitherik.com):