In this guide, you’ll learn how to authenticate to Firebase using your ESP32 or ESP8266 board with an email and password, and get the user UID. This is useful for restricting or allowing access to certain users or creating multiple users that can access the same Firebase project. Additionally, this is helpful when setting up database rules to protect your project’s data.

Updated 30 April 2025.
Other Firebase Tutorials with the ESP32 that you might be interested in:
What is Firebase?
Firebase is Google’s mobile application development platform that helps you build, improve, and grow your app. It has many services used to manage data from any android, IOS, or web application like authentication, realtime database, hosting, etc. In this tutorial, we’ll focus on the authentication part.

Project Overview
- Create Firebase Project
- Set Authentication Methods
- Get Project API Key
- Authentication with ESP32/ESP8266
1) Create Firebase Project
Follow the next instructions to create a new project on Firebase.
- Go to Firebase and sign in using a Google Account.
- Go to the Firebase Console and create a new project.
- Give a name to your project, for example: ESP-Project, and click Continue.
- Next, enable or disable AI assistance for your project. This is optional.
- Disable the option Enable Google Analytics for this project, as it is not needed. Then, click Create project.
- It will take a few seconds to set up your project. Click Continue when it’s ready.
- You’ll be redirected to your Project console page.
2) Set Authentication Methods
To allow authentication with email and password, first, you need to set authentication methods for your app.
“Most apps need to know the identity of a user. In other words, it takes care of logging in and identifying the users (in this case, the ESP32 or ESP8266). Knowing a user’s identity allows an app to securely save user data in the cloud and provide the same personalized experience across all of the user’s devices.” To learn more about the authentication methods, you can read the documentation.
- On the left sidebar, click on Build > Authentication and then on Get started.
- There are several authentication methods like email and password, Google Account, Facebook account, and others.
- Select Email/Password and enable that authentication method. Then, click Save.
- Then, at the top, click on the Users tab. Then, click on Add user.
- Create a new user with an email and password. The email can be your personal email. Create a password for that user (you need to remember the password later). Finally, click on Add user.
- The User will show up on the list of users. You can see information about the user, like when it was created, the last time it signed in, and its user UID.
Firebase creates a unique UID for each registered user. The user UID allows us to identify the user and keep track of the user to provide or deny access to the project or the database. There’s also a column that registers the date of the last sign-in. At the moment, it is empty because we haven’t signed in with that user yet.
3) Get Project API Key
To interface with your Firebase project using the ESP32 or ESP8266 boards, you need to get your project API key. Follow the next steps to get your project API key.
- To get your project’s API key, on the left sidebar click on Project Settings.
- Copy the API Key to a safe place because you’ll need it later.
4) Authentication with ESP32/ESP8266
Now that your Firebase Project is created and you’ve set up the authentication method, you’ll learn to log in with the ESP32 or ESP8266 using the authorized user email and password.
To program the boards, you can use Arduino IDE, VS Code with the PlatformIO or pioarduino extensions, or other suitable software.
Note: for firebase projects, we recommend using VS Code with the PlatformIO or pioarduino extension because if you want to develop a web application to make the bridge between the ESP and Firebase, VS Code provides all the tools to do that. However, we won’t build the web application in this tutorial, so you can use Arduino IDE.
Installing the FirebaseClient Library
To use Firebase with the ESP32 and ESP8266, we’ll use the FirebaseClient library. This library is compatible with the ESP32, ESP8266, and many other boards.
Installation – VS Code + PlatformIO
If you’re using VS Code with the PlatformIO extension, click on the PIO Home icon and then select the Libraries tab. Search for “FirebaseClient“. Select the Firebase Client Library by Mobitz.

Then, click Add to Project and select the project you’re working on.

Also, change the monitor speed to 115200 by adding the following line to the platformio.ini file of your project:
monitor_speed = 115200
Installation – Arduino IDE
If you’re using Arduino IDE, follow the next steps to install the library.
- Go to Sketch > Include Library > Manage Libraries
- Search for FirebaseClient and install the FirebaseClient by Mobitz. We’re using version 2.0.3.

ESP32/ESP8266 Firebase Authentication Email/Password (Get User UID)
Copy the following code to the Arduino IDE or to the main.cpp file if you’re using VS Code.
/*
Rui Santos & Sara Santos - Random Nerd Tutorials
Complete project details at our blog: https://RandomNerdTutorials.com/esp32-esp8266-firebase-authentication/
Based on this example: https://github.com/mobizt/FirebaseClient/blob/main/examples/App/AppInitialization/UserAuth/UserAuth.ino
*/
#include <Arduino.h>
#if defined(ESP32)
include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <WiFiClientSecure.h>
#include <FirebaseClient.h>
#include "ExampleFunctions.h" // Provides the functions used in the examples.
// Network and Firebase credentials
#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"
#define Web_API_KEY "REPLACE_WITH_YOUR_FIREBASE_PROJECT_API_KEY"
#define USER_EMAIL "REPLACE_WITH_FIREBASE_PROJECT_EMAIL_USER"
#define USER_PASS "REPLACE_WITH_FIREBASE_PROJECT_USER_PASS"
// User functions
void processData(AsyncResult &aResult);
// Authentication
UserAuth user_auth(Web_API_KEY, USER_EMAIL, USER_PASS);
// Firebase components
FirebaseApp app;
WiFiClientSecure ssl_client;
using AsyncClient = AsyncClientClass;
AsyncClient aClient(ssl_client);
AsyncResult dbResult;
bool taskComplete = false;
void setup(){
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(300);
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP());
Serial.println();
// Configure SSL client
ssl_client.setInsecure();
#if defined(ESP32)
ssl_client.setConnectionTimeout(1000);
ssl_client.setHandshakeTimeout(5);
#elif defined(ESP8266)
ssl_client.setTimeout(1000); // Set connection timeout
ssl_client.setBufferSizes(4096, 1024); // Set buffer sizes
#endif
// Initialize Firebase
initializeApp(aClient, app, getAuth(user_auth), processData, "🔐 authTask");
}
void loop(){
// Maintain authentication and async tasks
app.loop();
// Check if authentication is ready
if (app.ready() && !taskComplete){
taskComplete = true;
// Print authentication info
Serial.println("Authentication Information");
Firebase.printf("User UID: %s\n", app.getUid().c_str());
Firebase.printf("Auth Token: %s\n", app.getToken().c_str());
Firebase.printf("Refresh Token: %s\n", app.getRefreshToken().c_str());
print_token_type(app);
}
}
void processData(AsyncResult &aResult){
if (!aResult.isResult())
return;
if (aResult.isEvent())
Firebase.printf("Event task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.eventLog().message().c_str(), aResult.eventLog().code());
if (aResult.isDebug())
Firebase.printf("Debug task: %s, msg: %s\n", aResult.uid().c_str(), aResult.debug().c_str());
if (aResult.isError())
Firebase.printf("Error task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.error().message().c_str(), aResult.error().code());
if (aResult.available())
Firebase.printf("task: %s, payload: %s\n", aResult.uid().c_str(), aResult.c_str());
}
You need to insert your network credentials, URL database, and project API key for the project to work.
How the Code Works
Continue reading to learn how the code works, or skip to the demonstration section.
Include Libraries
First, include the required libraries. The WiFi.h library to connect the ESP32 to the internet (or the ESP8266WiFi.h library for the ESP8266 board), the FirebaseClient.h and WiFiClientSecure libraries to interface the boards with Firebase. We also include the ExampleFunctions.h file which is included in the library that comes with some additional functions for this example.
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <WiFiClientSecure.h>
#include <FirebaseClient.h>
#include "ExampleFunctions.h" // Provides the functions used in the examples.
Defining Credentials
Include your network credentials in the following lines.
#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"
Insert your Firebase project API key.
#define Web_API_KEY "REPLACE_WITH_YOUR_FIREBASE_PROJECT_API_KEY"
Set the Firebase email user and corresponding password.
#define USER_EMAIL "REPLACE_WITH_FIREBASE_PROJECT_EMAIL_USER"
#define USER_PASS "REPLACE_WITH_FIREBASE_PROJECT_USER_PASS"
Declaring Firebase Authentication and Components
The following line creates an authentication object using the project API key, the project user email, and password.
UserAuth user_auth(Web_API_KEY, USER_EMAIL, USER_PASS);
This creates a FirebaseApp instance called app that refers to the Firebase application.
FirebaseApp app;
The following lines set up the asynchronous communication framework for interacting with Firebase’s Realtime Database. Basically, you create an SSL client using the WiFiClientSecure library. Then, you instantiate an Asynchronous client called aClient that enables secure HTTPS. This will allow you to handle network operations asynchronously.
WiFiClientSecure ssl_client;
using AsyncClient = AsyncClientClass;
AsyncClient aClient(ssl_client);
setup()
In the setup(), initialize the Serial Monitor and connect the board to your Wi-Fi network.
void setup(){
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(300);
}
Serial.println();
Configure the SSL Client (different for ESP32 and ESP8266).
// Configure SSL client
ssl_client.setInsecure();
#if defined(ESP32)
ssl_client.setConnectionTimeout(1000);
ssl_client.setHandshakeTimeout(5);
#elif defined(ESP8266)
ssl_client.setTimeout(1000); // Set connection timeout
ssl_client.setBufferSizes(4096, 1024); // Set buffer sizes
#endif
The following line initializes the Firebase app with authentication and sets the processData() as the callback function for async results (this means that any results from the initializeApp() function will be handled on the processData() callback function).
initializeApp(aClient, app, getAuth(user_auth), processData, "🔐 authTask");
loop()
The Firebase library we’re using works asynchronously and with callback functions. This means that when an event happens, the corresponding assigned callback functions will run. To keep the Firebase app running, handling authentication and asynchronous tasks, we need to add app.loop() at the start of our loop() function.
void loop(){
app.loop();
The app.ready() command checks if Firebase authentication is complete and ready, so that we can proceed with other Firebase operations (like getting the User UID). We also have a control variable taskComplete so that is just runs once to print the user UID.
if (app.ready() && !taskComplete){
taskComplete = true;
Then, we can get the user UID with app.getUid().
Firebase.printf("User UID: %sn", app.getUid().c_str());
We also print more information about the app auth token.
Firebase.printf("Auth Token: %sn", app.getToken().c_str());
Firebase.printf("Refresh Token: %sn", app.getRefreshToken().c_str());
print_token_type(app);
Demonstration
After uploading the code, open the Serial Monitor at a baud rate of 115200.
Note: if you’re using VS Code, you need to add the following line to your platformio.ini file to change the baud rate. Then, save your file.
monitor_speed = 115200
Reset your board by pressing the on-board EN/RST button.
The ESP32/ESP8266 authenticates successfully and prints information about the user UID and the authentication token.

Then, go to your Firebase project console to check if it signed in as a user. Go to Authentication > Users. You should have the current date in the Signed In field. Additionally, you’ll see that the User UID matches the UID printed by your ESP board in the Serial Monitor.

Congratulations! You successfully signed in your ESP32/ESP8266 board as a user. You can combine this example with one of our previous tutorials to send sensor readings to the database as an authorized user: ESP32: Getting Started with Firebase (Realtime Database) or you can follow this project:
Wrapping Up
In this tutorial, you learned how to set up the ESP32/ESP8266 board as a user that can access your Firebase project with email and password. This was just a simple example that you can apply to more advanced projects.
Setting up the ESP as a user allows you to identify the user to enable or restrict access to the Firebase Project or to the database or to specific database nodes—allows you to set up database rules.
We have a project that shows how to use this feature to create database rules and to build a web app with login/logout features to authorize and restrict access to the data. You can check it out on the following link:
If you want to learn more about building a fully-featured Firebase Web App to control and monitor your ESP32 and ESP8266 boards from anywhere, take a look at our eBook:
Other resources that you might find helpful:
Please create the tutorial for run time wifi credentials addition .it hard to add the wifi password and I’d hard-coded for scalable product
Hi.
You can use the WiFi Manager library.
For example: https://github.com/zhouhan0126/WIFIMANAGER-ESP32
Regards,
Sara
Excellent tutorial! Would this solution work for multiple users using the same email address/password? For example, if a user has multiple ESP-32 devices in their home and wanted to connect all of them to the database, can each ESP-32 have the same email/password?
Yes.
That is possible.
Regards,
Sara
Hey Sara, great job!
Thank you 🙂
Great work you have done here, but there is 1 issue actually which is:
Error compiling for board NodeMCU 1.0 (ESP-12E Module).
Hi.
What is exactly the error?
What line is highlighted by the error?
Regards,
Sara
Actually just commented with an error but i solved it now it’s okay.
But now how can we add and fetch data to this specific uid in arduino?
Hi.
You can try to combine this example with the following:
– https://randomnerdtutorials.com/esp32-firebase-realtime-database/
You have the retrieved UID, you just need to modify the path where you’ll write to include the UID.
We’ll post a more complete tutorial soon.
Regards,
Sara
Hey Sara, thank you so much i’m actually trying really hard to figure it out how to add and fetch data combining these 2 projects.
Honestly i’m still too fresh on arduino came from flutter programming but however i’m willing to learn so, i hope you could help me with this! it might be simple to you but to me because i’m fresh it will take some guidance at first then everything will be alright.
So if you would help i will appreciate it if you couldn’t then i will wait for the tutorial.
Thaaaaank you so much
Hi.
You can also take a look at this example: https://github.com/mobizt/Firebase-ESP-Client/blob/main/examples/RTDB/Basic/Basic.ino
The tutorial should come out this month or at the beginning of next month.
Regards,
Sara
Have you made the totorial on retrieving the data from database after logging in with email and password
thank you for this job,
i live in rwanda country but our iot technology is very low please how can you help us to develop many company to make many projects for handling or to solve many problems can be solved through iot technology in our country.
good job 👏 keep up the good work
Hola Sara! como estas! estoy muy satisfecho en haber comprado tu tutorial de inicios con Firebase width Esp8266! Quiero consultarte como hago para agregar mas de un usuario autorizado para poder realizar cambios en el esp8266. En concreto, quiero solo agregar o quitar los usuarios desde la consola firebase , en el codigo que viene en el tutorial solo tiene acceso un solo usuario dentro del codigo del esp8266.
Saludos ! espero que me puedas guiar !
Hi.
To add more users you need to organize the database in a different way and also change the database rules.
At the moment, I don’t have any tutorials that explain how that works.
Regards,
Sara
Hi,
Thanks for this amazing tutorial.
I have make one firmware wirh this, combined to send water analysis, work 58 minutes, after data transfer is blocked. I have to re login one times once every 58 minutes?
Thanks in advance
Hi.
Do you get any more information on the serial monitor?
Regards,
Sara
Hi Sara,
Thanks for your reply.
Yes, after 58 minutes Serial monitor show
Failed
Reason: Token is not ready!
Thanks in advance
Hi.
Here’s the same issue: https://github.com/mobizt/Firebase-ESP-Client/discussions/62
I think you need to update your library.
Regards,
Sara
Hi,
Thanks for tutorial.
I am also facing the same problem after 1 hour I tried to control from firebase, esp not responding. serial monitor freeze with lost GPIO message and try to reopen the serial monitor still no response. after hardware rest or repowering, the ESP will work normally, again after 1 hour facing same problem
Hi.
Are you using ESP32 or ESP8266?
Regards,
Sara
I tried on both boards. I am facing the same issue.
Hi.
Try this suggestion from one of our readers:
“Hi, I solved this problem by putting this code in loop, I think maybe there’s a better solution but that works for now, it is because the tokan is expired and nothing is called after than to refresh it
if(Firebase.isTokenExpired())
Firebase.refreshToken(&FirebaseConfigObj);
“
Hi!
I have solved with this lines:
https://github.com/mobizt/Firebase-ESP-Client/blob/60680080caf053db16106f63b20df1163324527b/examples/RTDB/Basic/Basic.ino#L144-L149
Hi,
Thank you, i already found this solution. But when i try to combine those codes (this and that) i am facing error. Can you help with that?
Hi sara,
Thank you for your reply i tried this in loop but i facing error :exit status 1
‘FirebaseConfigObj’ was not declared in this scope; did you mean ‘FirebaseConfig’? i tried also (&FirebaseConfig, &auth)
Try
(&config, &auth)
Hi,
Thank you, Error: no matching function for call to ‘Firebase_ESP_Client::refreshToken(FirebaseConfig*, FirebaseAuth*)’
Hi Sara,
After a long research I found a solution, but I facing error can you plz help with that.
https://github.com/mobizt/Firebase-ESP-Client/blob/60680080caf053db16106f63b20df1163324527b/examples/RTDB/Basic/Basic.ino#L144-L149
https://create.arduino.cc/projecthub/embeddedlab786/iot-and-manual-switch-control-home-appliances-using-firebase-c90418
Hi.
Add something like this in the loop():
if firebase.ready()
return
Regards,
Sara
Hi Sara,
Thank you for your reply. After a long search finally found a solution and tested also(after 10 days still running with no issue)
loop()
if(Firebase.isTokenExpired())
firebase.ready()
Instead of filling in the API_KEY statically, I can set it dynamically so that it can be changed via the app or web, for example.
Can you suggest me how to do it?
How can we achieve this with any sim module?
Hi, I encountered a weird error…. it logs in normally for the auth but after a while the connection gets refused by firebase. I thought the reason being the token’s expiration, but it keeps saying that the tokes aren’t expired yet.
Maybe a bug with the library?
Anyone who’ve done this using SIM800 or similar?
Thanks it workes great can you please help with retreiving data from the realtime Database with the authentication?
Good day I am trying to read data from realtime Database in firebase but my code gives permission denied.I am able to authenticate the esp32 and sign it in to firebase and post data to the database my problem is when I try to read data from the database.This is the code block that is supposed to retreive the data.
I want to retreive the depth from the database .
Uid
Devices
device ID
-depth
void getValues()
{
if (Firebase.ready())
{
if (Firebase.RTDB.getString(&fbdo,uid +”/Devices/” + deviceID + “/depth”))
{
if (fbdo.dataType() == “string”)
{
depth= fbdo.stringData();
Serial.println(depth);
}
}
else
{
Serial.println(fbdo.errorReason());
}
}
else
{
Serial.println(fbdo.errorReason());
}
}
Capture