To understand Single Page Application we need to first understand what was the traditional way websites used to work. In older websites each page on website was requested separately.
This pattern is called as Multiple-page app(MPA)
.
In Multiple-page app(MPA) every change displays the data or submits data back to server requests rendering a new page from the server in the browser
Single page application(SPA)
is an app that doesn't need to reload the page during its use and works with the browser. Think of all the apps like Google Maps Gmail a Facebook event GitHub all these are the examples of single page application.
The main advantage of single-page applications is its speed. The benefit of using single page applications is the user experience(UX)
where the user doesn't have to wait a lot for page reloads or navigation
From developers perspective is very easy to debug a single page applications you can use special tools for build for angular react view of you can use Chrome console and monitor Network operations
Amazon CloudFront is a web service that speeds up distribution of your static and dynamic web content, such as .html, .css, .js, and image files, to your users.
In case of SPA this delivers all the html files and JS bundles(heavy in size) quickly to client devices.
When you request for a resource from cloudfront it returns a cached version of that file to your browser. When you want to load an internal route/URL path on your website that only your SPA understands. Cloudfront can not return any response to that. Because it has no corresponding file for that resource
Ex. Steps in case of path matches file present in Cloudfront cache
hostname/index.html
index.html
file in cacheSteps in case of path matches file NOT
present in Cloudfront cache
hostname/home
home.html
home.html
Above issue arises due to the behaviour of SPA, The internal routing is handled in client side. But because the internal route/URL path is requested before the SPA has loaded in browser, cloudfront thinks that this is a unknown route and returns AccessDenied response.
The solution
is to make browsers aware of the routing before requesting the internal routes.
To achieve this we can redirect the unknown route paths to homepage( index.html
). This makes sure we load the JS bundles necessary for internal routing.
With this config, Cloudfront will not return error but will respond with index.html
page.
Now browser will load this page and handle the internal redirect in browser.