SPA Frontend & Backend Architecture


You cannot hide an API Key or an API URL when you have a frontend constructed in pure HTML/JavaScript like most SPAs. SPA inherently loads in the browser, for this reason using middleware or environment variables such as Dotenv in Node.js will not work. You can always use the browser Network tab or a tool like Fiddler to expose where web calls are being made. To solve this, a relay or proxy server needs to be used.

Web API Relay Server

Visual Studio 2022 Preview 2 supports a Client/Server architecture with Vue.js and Web API as a backend relay server.

The steps are documented in Microsoft’s article:

  1. Create an ASP.NET Core app with Vue in Visual Studio
  2. Create a minimal web API with ASP.NET Core

Note that in the first link, Microsoft documents Web API using an MVC pattern, the documentation below focuses on Minimal APIs.

Quick Setup

Frontend Design

Create a new Visual Studio 2022 project, search for Vue and then select the Standard template. Next, choose .NET as a backend framework. Once the project has been created, run it to ensure the SPA loads correctly.

Backend Design

Create a new ASP.NET Core Web API project.

Uncheck ‘Use controllers (uncheck to use minimal APIs).

Ensure that the project is published correctly.

Integrate Frontend & Backend

Open vue.config.js

module.exports = {
    devServer: {
        https: {
            key: fs.readFileSync(keyFilePath),
            cert: fs.readFileSync(certFilePath),
        proxy: {
            '^/weatherforecast': {
                target: 'https://localhost:5001/'
        port: 5002

Notice on line 9, a proxy request is made to the endpoint:

        proxy: {
            '^/weatherforecast': {
                target: 'https://localhost:5001/'

This point to the Backend server route with port 5001 under HTTPS. To ensure the SPA is routed correctly, we need to ensure that the backend API matches the correct ports.

Open launchSettings.json and edit the line:

"applicationUrl": "https://localhost:7220;http://localhost:5220",

To the following:

"applicationUrl": "https://localhost:5001;http://localhost:5003",

This sets the Web API to launch the HTTPS endpoint on the 5001 port, and the HTTP endpoint on the 5003 Endpoint.

Project Start-up

Ensure both projects start up successfully in the following order:

Run Project

Running the project should result in the following:

To Publish the project to Microsoft Azure, follow the steps that are documented in Create an ASP.NET Core app with Vue in Visual Studio.

Leave a comment