How to Share HTML Templates Between Vite Frontend and C# WebAPI in a Monorepo Setup?

Question:

I’m developing a website with the following structure:

  • Frontend: Vite + Nunjucks templates + Tailwind CSS + JavaScript
  • Backend: C# WebAPI

Goals

Here’s what I want to achieve:

  1. Backend returns HTML components – The WebAPI should be able to serve HTML strings.
  2. Monorepo for shared code – I’d like to manage everything in a monorepo.
  3. Avoid Razor pages – I don’t want to create a full Razor application.
  4. Frontend served from a CDN – The frontend should be built and deployed to a CDN, independent from the backend API deployment.

Current Setup

The setup is almost what I need, and works well for building and deploying the frontend separately to a CDN. The backend is a straightforward WebAPI. The main issue is that there’s no easy way to share or reuse templates between the frontend and backend, since I’m currently using separate repositories and Nunjucks for frontend templating.

Desired Solution

Ideally, I’d like a way to:

  1. Share templates across frontend and backend within a monorepo.
  2. Continue using Vite for frontend building and Nunjucks for templating, or something similarly lightweight.
  3. Allow the backend to render or compile HTML templates to strings that it can serve.

The approach I have in mind could involve compiling the templates in such a way that they’re compatible for both the frontend and backend, allowing HTML strings to be served from the backend. I know about server components, but that doesn’t quite fit my requirements.

Is there a feasible way to share templates between a Vite-based frontend and a C# WebAPI backend in this type of setup? Ideally, I’m looking for something that doesn’t add too much complexity.

Any insights or suggestions would be much appreciated!