Introduction:
Firebase is a powerful platform developed by Google that allows developers to build scalable and real-time web applications without the need for a backend infrastructure. In this tutorial, we will explore how to connect a NodeJS(ExpressJS) application to Firebase for data storage and retrieval. We will cover how to set up a Firebase project, use the Firebase Admin SDK to interact with the Firebase database, and deploy the application to test it locally and on a cloud platform.
Prerequisites:
Before we begin, make sure you have the following tools and technologies installed on your system:
- Node.js and npm (Node Package Manager)
- Firebase account and project
- ExpressJS framework
Setting Up Firebase Project:
- Go to the Firebase console (https://console.firebase.google.com/) and create a new project.
- Click on the "Web" option to register your web application.
- Copy the Firebase configuration snippet provided and save it for later use.
Setting Up NodeJS(ExpressJS) Application:
-
Create a new NodeJS project by running the following command in your terminal:
$ mkdir firebase-nodejs-app $ cd firebase-nodejs-app $ npm init -y
-
Install the required dependencies for the project:
$ npm install express firebase-admin
- Create an ExpressJS server in your
index.js
file:const express = require('express'); const app = express();
app.get(‘/’, (req, res) => {
res.send(‘Hello, world!’);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(Server is running on port ${PORT}
);
});
4. Initialize Firebase Admin SDK in the `index.js` file using the Firebase configuration snippet you copied earlier:
```javascript
const admin = require('firebase-admin');
const serviceAccount = require('./path/to/serviceAccountKey.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://your-project-id.firebaseio.com'
});
- Start the Express server by running the following command:
$ node index.js
Connecting to Firebase Database:
Now that we have set up the Firebase project and initialized the Firebase Admin SDK in our NodeJS application, we can start storing and retrieving data from the Firebase database.
-
Create a reference to the Firebase database in your
index.js
file:const db = admin.firestore();
-
Add a route to save data to the Firebase database:
app.post('/data', (req, res) => { const { name, age } = req.body; db.collection('users').add({ name, age }) .then(() => { res.send('Data saved successfully!'); }) .catch(error => { console.error('Error saving data:', error); res.status(500).send('An error occurred while saving data.'); }); });
- Add a route to retrieve data from the Firebase database:
app.get('/data', (req, res) => { db.collection('users').get() .then(snapshot => { const data = []; snapshot.forEach(doc => { data.push(doc.data()); }); res.json(data); }) .catch(error => { console.error('Error retrieving data:', error); res.status(500).send('An error occurred while retrieving data.'); }); });
Testing Locally:
To test the application locally, open your browser and navigate to http://localhost:3000
to see the "Hello, world!" message. You can also use tools like Postman to send POST requests to http://localhost:3000/data
and GET requests to http://localhost:3000/data
to store and retrieve data from the Firebase database.
Deploying to a Cloud Platform:
Once you have tested the application locally and ensured that it is working correctly, you can deploy it to a cloud platform like Google Cloud Platform or Heroku for public access.
-
Create a deployment script in your
package.json
file:"scripts": { "start": "node index.js" }
-
Create a Procfile in the root directory of your project with the following content:
web: npm start
- Deploy the application to your preferred cloud platform following their deployment instructions.
Conclusion:
In this tutorial, we have explored how to connect a NodeJS(ExpressJS) application to Firebase for data storage and retrieval. We have covered setting up a Firebase project, initializing the Firebase Admin SDK, and deploying the application to test it locally and on a cloud platform. By following these steps, you can build scalable and real-time web applications using Firebase and NodeJS.
공개 프리뷰 버전으로 업데이트 된 Firebase Data Connect 서비스를 NodeJS(ExpressJS)에서 연결하여 테스트하는 과정을 녹화하였습니다.
🔗 Doc.
https://firebase.google.com/docs/data-connect/admin-sdk?authuser=0
🔗 NodeJS(ExpressJS) Code
https://gist.github.com/doyle-flutter/8970c926b6981143d0c59dcd4ce8e34d
* 온오프라인 수업 :
– https://smartstore.naver.com/momond/products/7198247321
– https://taling.me/Talent/Detail/10726
* contact : afzxc@naver.com
Thanks for uploading this!