Vue.js Server-side-rendering with Asp.Net Core

Server-side-rendering (SSR) guarantees a better level of SEO than client-side-rendering. There are a few tools that allow Vue.js run in the server like Nuxt.js for example, which allows us to render part of the content of our components server side.

This is a good solution in most cases, but this solution didn’t work in our case. We wanted to render and serve components in Vue.js using an MVC built with Asp.Net Core. We are going to show you how you can render single file components with the .Net Core ecosystem.

The tools we used are:

MVC in Asp.Net Core 2.1

Nuget Package Microsoft.AspNetCore.NodeServices(latest version)

How to run it:

NodeServices lets us run node in an asynchronous form as well as injecting it.

Here we can see what the dotnetAdapter.js does

The only thing we add is a reference to the RenderEngine, where we have all the logic of running the render function. In this way we can separate .NET from nodeServices.

The renderEngine takes charge of returning the final string importing our bundle, which we obtain the moment we run webpack and call vue-server-renderer. This library allows us to render a string which is what we need.

Webpack and our components in Vue.js

The bundle is the sum of our components + the initialiser (entry-server.js):

App.vue

Here we have a simple component that at the same time imports another component.

HelloWorld.vue

And to complete the template of the page:

Following the recommendations that ssr.vuejs.org gives us, we leave the comment of vue-ssr-outlet in the body which will later be substituted with our code.

To generate the bundle we use vue-loader in our webpack:

The result:

And our html code:

If you are interested in learning more about Vue.js or JavaScriptServices in Net here are some links to their documentation:

Vue loader: https://vue-loader.vuejs.org/guide/#vue-cli

Vue ssr: https://ssr.vuejs.org

NodeServices: https://github.com/aspnet/JavaScriptServices