Search code examples
javarestfirebasejersey

Where to initialize Firebase Admin SDK in Java REST API?


I am developing a REST API using Java, with the Jersy. The REST API will be used by a Fluttervmobile app.

I have decided to use Firebase in my application. So the mobile app will use Firebase Authentication. However the Firebase functions are only to authenticate the user at the moment, all other data are in a MySQL database which is accessible via the REST API.

Now, I installed the Firebase Admin SDK according to this link - https://firebase.google.com/docs/admin/setup

The below is the code to initialize the app

try
        {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            InputStream serviceAccount = classLoader.getResourceAsStream("xxxxxx.json");

            FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                .build();

            FirebaseApp.initializeApp(options);
        }
        catch(IOException io)
        {
            io.printStackTrace();
        }

My problem is, in which class should put this code in? I can use the rest filter classes to validate the token sent by the Firebase and initialize it at the same time. However this means if I get 1M requests, Firebase will be initialized for 1M times!

How can I solve this matter?


Solution

  • You initialize the Firebase Admin SDK just once per process per project that needs to be accessed. If you have once process and one project to access, initialize it just once in that process, before it's first used.