gonext.jsgo-echo

How to handle SPA urls correctly in Golang?


I am trying to embed and serve my frontend (nextjs with static export) with echo. I am currently using:

//go:embed all:frontend/out
var FrontendFS embed.FS

func BuildFrontendFS() http.FileSystem {
    build, err := fs.Sub(FrontendFS, "frontend/out")
    if err != nil {
        log.Fatal(err)
    }
    return http.FS(build)
}

e := echo.New()

e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
    Filesystem: BuildFrontendFS(),
    HTML5:      true,
}))

e.Logger.Fatal(e.Start(":1323"))

It works great however when I try to open a url like localhost:1323/example it routes back to index.html. The problem is that there is a page called example.html and I am expecting to see that page instead. If I call the url like localhost:1323/example.html it works.

Any ideas how I can solve this so that I can just use localhost:1323/example ?


Solution

  • I see an ./out directory being referenced, so it looks like you're exporting to static HTML. If that's the case, enable the trailingSlash setting in your next.config.js:

    module.exports = {
      trailingSlash: true,
    }
    

    ./example.html will become ./example/index.html after the export.