Right now I'm trying to understand how Firebase authentication works on the backend. It seems like the main method is for the web client to get an id token, and then for every REST request, inject that token into the Authorization http header before sending the request to the backend (official docs, official docs 2, SO answer). Just as a starting point, I cloned a super basic Github project (teroyks - firebase-auth-api) that uses this method, and you can see how the id token injection works on the frontend:
// fetch timestamp from API
// authenticate API request with JWT auth token
const fetchFromApi = userIdToken => {
return fetch('/api', {
headers: {
Authorization: `Bearer ${userIdToken}`,
},
})
.then(response => {
...
You can find the full code in the github: frontend backend
However, I'd like to be able to create pages on my website that are only accessible by signed-in users. For example, the path https://www.mywebsite.com/profile should display the current user's profile, and if they aren't authenticated, redirect them to login. But I haven't seen any firebase examples that do this. If the user clicks on a link that goes to https://www.mywebsite.com/profile (maybe it's in their bookmarks or something), the browser makes the GET request and not me, so I have no way of injecting the id token to the request. One workaround I've thought of is to just load a blank page on the initial request, and then the blank page runs the client side code needed to get the id token and retrieve the actual page content from the backend, but this feels very hacky and would prevent server-side rendering. What's the standard way of solving this issue?