Back to Jots

Prevent Chrome from displaying API Response JSON when a user presses the Back button

Sometime ago, we ran into a bug where Google Chrome displayed an API response JSON instead of HTML when a user pressed the Chrome’s Back button to navigate back to the previous page. Since this caused our customers to consider our app to be unpolished/dysfunctional, we decided to resolve the bug immediately. Examining the Network panel, we found that when a user pressed the back button, Chrome rendered the previous page from its cache In our app, HTML pages and API requests have the same URLs. When a customer visits the /emails URL in their browser, the server responds with HTML. The page’s JavaScript then hits the /emails API endpoint to retrieve the user’s emails. When a customer clicked on any link on the page and then navigated back by pressing the Back button, Chrome displayed the API response JSON of the /emails API endpoint. We found this was because the /emails URL responded with JSON the last time Chrome sent a request to that URL. After googling a bit, we learnt that Chrome’s caches a page using just the URL and the request method (GET, POST etc.) but not the Accept: application/json header (which is sent for an API request but not a HTML request). A straightforward way to resolve this problem was to simply change our API request URLs slightly and we did just that. We modified the page’s JavaScript to add a is_api_request=true query param to all API endpoints changing the URL of all our API endpoints.

$.ajaxSetup({
 data: {is_api_request: true}
});

Since API requests and HTML pages now have different URLs, Chrome started to correctly render the previous page when a user presses the Back button.

A straightforward problem to resolve but many happy customers :)

Built with Hugo & Notion. Source code is available at GitHub.