How to Serve an SPA (React/Vue) from a Go Backend

Web
Serve a React or Vue SPA from Go by mounting a static file server and adding a fallback handler to return index.html for all non-file routes.

Serve an SPA from a Go backend by mounting a static file handler for the built frontend assets and adding a fallback handler to return index.html for all other routes.

package main

import (
	"net/http"
	"path/filepath"
)

func main() {
	fs := http.FileServer(http.Dir("./dist"))

	mux := http.NewServeMux()
	mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if filepath.Ext(r.URL.Path) != "" {
			fs.ServeHTTP(w, r)
			return
		}
		http.ServeFile(w, r, "./dist/index.html")
	}))

	http.ListenAndServe(":8080", mux)
}
  1. Build your React or Vue app to a dist directory containing index.html and assets.
  2. Run the Go server above to serve static files and fallback to index.html for client-side routing.