Application 2018-06-06

Challenges Faced When Building an SPA

Fix SPA routing and resource path issues with nginx try_files configuration for single-page application development.

Read in: ja
Challenges Faced When Building an SPA

Overview

Previously, I wrote an article titled Directory Structure and nginx conf File Considerations When Integrating SPA into Laravel, but the nginx conf described there was insufficient, so I revisited and resolved the issues.

Prerequisites

Challenges Faced When Building an SPA

nginx Configuration

You need to configure it to always return index.html even after a reload. Use try_files in the conf like this:

location / {
        try_files $uri $uri/ /index.html;
}

Paths for JS Files and Other Sources

In index.html, the path for JS files was specified as:

<script type="text/javascript" src="./dist/bundle.js"></script>

This caused resources to be returned as /dashboard/post/dist/bundle.js when accessing /dashboard/post, etc. I changed it to an absolute path to always reference bundle.js regardless of the URI.

<script type="text/javascript" src="/dist/bundle.js"></script>

Thoughts

It took quite some time to resolve, but by separating the issues between nginx and the application, I was able to understand it quickly.

References

Tags: Nginx SPA
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles