ESC
React Native Starter AI logo
Menu
On this page

Tutorials > Protected API Calls

Go to the react-native-starter-backend/functions/src/index.ts file. That will be the file that you will store all of your API endpoints.


1. We mostly need protected API endpoints for the general cases such as Please Login , Paid Plan Required to use this feature etc.


2. Adding a new protected API endpoint is pretty easy. You can create it like below and add the user check if the user is authenticated or not. validateFirebaseIdToken function automatically decides if the user is authenticated or not by checking the HTTP headers by itself; so you don't need to worry about that!


react-native-starter-backend/functions/src/index.ts
1import { validateFirebaseIdToken } from "./utils/validate-firebase-id-token"; 2 3export const protectedApiExample = onRequest(async (request, response) => { 4 const user = await validateFirebaseIdToken(request, response); 5 6 if (!user) { 7 response.status(403).send("unauthenticated") 8 return; 9 } 10 11 response.json({ 12 status: "user is authenticated!!!" 13 }) 14});

🔙 On the mobile app side, you just need to pass the authorization token as below. The existing HTTP services in the mobile app repository are already configured to work like this; but when you create a new one and need that to be protected; it is as easy as it seems below:


/react-native-starter-mobile/services/protected-api-sample.service.ts
1import apiClient from "./api"; 2 3import auth from "@react-native-firebase/auth"; 4 5export const protectedApiSampleService = async () => { 6 const idToken = await auth().currentUser?.getIdToken(); 7 return apiClient.post("/protectedApiExample", {}, { 8 headers: { 9 Authorization: `Bearer ${idToken}` 10 } 11 }); 12};