Host a Single-Page Application¶
Many web applications built with modern frameworks, like React, Vue, and Angular, are single-page applications (SPAs) that dynamically handle routing and rendering client-side instead of fetching each rendered page from the server. You can use MongoDB Realm to host your SPA and serve it to clients.
To host your app, you need to specify that it's a SPA in Realm. By default, Realm handles requests for a given resource by returning the file hosted at the specified resource path or a 404 if no file matches the path. However, SPAs render in a single, specific HTML file so all requests should return that file regardless of the requested resource path.
This guide covers how you can configure Realm Hosting to redirect all resource requests to a single file to support the SPA pattern.
Upload Your Built Application to Realm¶
Single-page applications render in a single, specific HTML file,
/index.html. The file should include the necessary
<script> tag or imported from an external file. You'll also
need to host any resources that you don't intend to access through a
When you are ready to host your SPA, run your application's build script and then upload the build folder to MongoDB Realm.
Configure Realm to Serve Your Application¶
Once you've started hosting your application files, you can immediately access your SPA by requesting the root HTML file directly. However, a request to any path other than the root file will return a 404. This can break the expected behavior of a SPA that uses a client-side router or otherwise relies on the URL path.
To configure Realm to serve the SPA's root page for all requests:
- Navigate to the Hosting page in the Realm UI and then click the Settings tab.
- Ensure that you have not specified a custom 404 page. If custom 404 is enabled, click the trash can icon () next to the specified 404 page.
- Next to Single Page Application, click Choose File. Choose the root HTML file for your SPA and then click Select.
- Click Save.