URL shortner using NodeJS and firebase
Published: 2021-07-22 11:33:40


Hello Guys,
I will show you how you can make a simple url Shortner using Nodejs And firebase.

#1 Create a project in firebase
First create a new project in firebase and give it a name what ever you like.
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c02jfdmk8doezfl66o56.png)
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zg66cd2ar99xtrdzg68p.png)
  
Now create a Realtime database in firebase and select any server you want.
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oqvkr14h01so2424zdj6.png)
 
Goto project settings and register your project as a web app.
After registering firebase will give config details of your app.
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0xftq3vsg5a6d9894rsv.png)
 
#2 Creating Backend Using NodeJS and ExpressJs
Now open VS code and create a new folder
In that folder create a JavaScript file Backend.js and Firebase.js
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ydyw7vgokp4o83om88dg.png)
 
We can also do it in single file but its good practice to separate different components of your app in different files.
Now first initialize you NPM and Download some dependencies.
Open terminal by pressing ctrl+shift+'

```
npm init
npm install express
npm install firebase
```
Now copy your firebase config details and create a new map in firebase.js file and paste it.
Now add this two lines at the top of firebase.js so that we can user firebase and realtime database.
```
var firebase = require("firebase/app");
require("firebase/database");
```
Now initialize firebase and export it so that we can use it in backend.js
And at last your firebase.js will look like this
```
var firebase = require("firebase/app");
require("firebase/database");

var firebaseConfig = {
    apiKey: "",
    authDomain: "urlshortner.firebaseapp.com",
    databaseURL: "https://urlshortner-rtdb.firebaseio.com",
    projectId: "urlshortner",
    storageBucket: "urlshortnerappspot.com",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
  };

  // Initialize Firebase
firebase.initializeApp(firebaseConfig);

const database = firebase.database();

module.exports = {firebase,database};
```
Now this is the backend.js file
```
const express = require('express')
var app = express()
const path = require("path");
const {firebase,database} = require("./firebase");



app.use(express.json());
app.use(express.urlencoded());
app.use(express.static(path.join(__dirname, 'views')));
app.set('view engine', 'ejs')

app.listen(5003, (err) => {
console.log("APPLICATION IS RUNNIG");
})

app.get('/', (req, res) => {

    res.render('index')

})
app.get('/favicon.ico', (req, res) => {

    res.status(404).send("");


});



app.post('/process', (req, res) => {
    console.log("post method")
const urlRegEx = "http|https?:\/\/(www\.)?[-a-zA-Z0–9@:%._\+~#=]{1,256}\.[a-zA-Z0–9()]{1,6}\b([-a-zA-Z0–9()@:%_\+.~#?&//=]*)";
var regEx = new RegExp(urlRegEx);
const longurl = req.body.longurl;

if (!longurl.match(regEx)) {
res.status(400).json({ message: "please enter valid url" });
return;
}

if (longurl.toString().length){
let shorturl =  (new Date()).getTime().toString(36);
addDatabaseEntry(shorturl, longurl);
res.status(200).json({
    longurl: longurl,
    shorturl: shorturl
})
}
})
app.get('/:shorturl', (req, res) => {
const url = req.params.shorturl;
database.ref().child("urls").child(url).get().then((snapshot) => {
if (snapshot.exists()) {
res.redirect(snapshot.val());
} else {
console.log("Wrong Url");
res.redirect('404');
}
}).catch((error) => {
console.error(error);
});
});
function addDatabaseEntry(shorturl, longurl) {
database.ref("urls/" + shorturl).set(longurl);
}

```
First 10 lines are the initialization of some packages. If you have some knowledge about http server then you will easily understand this code.

At first we are creating an http server at port 5003. Here we are only creating the Backend of the server . We are sending the long URL in the post request and then the server will verify if the URL is valid or not and if it is valid then it will generate a short URL for this long URL and store it in the database.

There are three main Functions in backend.js

1.addDatabaseEntry
2.Post request to generate short URL
3.Get request to redirect to long URL

addDatabaseEntry will take the long URL and short URL and store it in the database.

app.post will take a long URL and will first check if the URL is valid or not and if valid then it will create a short URL and add the entry to the database.

app.get will take the short URL from the user. if the URL is present in the database it will redirect the user to long URL and if URL is not present then it will give an error.
And that's all our URL shortner is ready. You can also get this code from my GitHub repository. Now lets give it some long URL.

[GitHub - urlshortener](https://github.com/aakashpsindhi/urlshortener)


#3 Testing
For testing I have created basic HTML page. If you want to see it you can get it on my GitHub. 
Entering Long URL
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gjsvyrmwwcotgdc7pfwx.png)
 
Converted to short URL
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/68ihogki31lo8p4hkcz6.png)
 
Redirect to long URL
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mjg7oe0g4o9wso7ptvd0.png)
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mgxlwr72sbtu4par1mbf.png)