Skip to content
Example of using Rust as serverMiddleware in Nuxt.js
Branch: master
Clone or download
Latest commit f8e5945 Mar 10, 2019
Type Name Latest commit message Commit time
Failed to load latest commit information.
middleware fix formatting Mar 10, 2019
src/pages add srcDir Mar 10, 2019
.gitignore add README Mar 10, 2019 fix readme Mar 10, 2019
package.json init package and deps Mar 10, 2019
yarn.lock init package and deps Mar 10, 2019

A word of caution: As noted in the Nuxt.js presentation at Vue.js Amsterdam 2019, the next major version of Nuxt will likely feature a new backend services framework much better than what's currently offered by Nuxt.js serverMiddleware.

Nevertheless, serverMiddleware can be a handy feature if you want to quickly embed a backend API into a Nuxt application without proxying requests to a separate API server (or resorting to programmatic Nuxt embedded in another Node.js server). See this article by Alexander Lichter for more considerations.

Nuxt serverMiddleware in Rust

Nuxt's underlying connect server works with Express.js-compatible middleware, that is, a function that takes three paramaters: request, response and next. In order to use Rust serverMiddleware, all we need is a native Node.js module that exports a function with that signature.

The Neon bindings for Node.js make this surprisingly easy. All I had to do to get the middleware folder of this sample repo started was typing neon new middleware. A good hour of reading through the docs and I was able to get a simple server middleware that adds a property to the response object:

fn middleware(mut ctx: FunctionContext) -> JsResult<JsUndefined> {
    let res = ctx.argument::<JsObject>(1)?;
    let next = ctx.argument::<JsFunction>(2)?;
    let message = ctx.string("Hello from Rust");
    res.set(&mut ctx, "neonMessage", message)?;
    let args: Vec<Handle<JsValue>> = vec![];
    let null = ctx.null(); ctx, null, args)?;

Running, in a nutshell:

yarn add global neon-cli --dev
cd middleware/
neon build
nuxt dev

Go to http://localhost:3000/.

You can’t perform that action at this time.