It's the weekend you are finally ready to deploy that particular side project so that you can show it to your peers and make it available so other fellow developers can test it. However, after several checks confirm that everything runs smoothly locally (hello localhost or should I say 127.0.0.1), but there seems to be a difficulty using your database functionalities in the deployed app. Hmm, I wonder what might be the problem?
This article profers several database solutions which are perfect for your little side projects and how you can get these databases up and running ASAP. Therefore, this article assumes that you :
- Have prior knowledge of how to build a web application.
- Understand and can implement database functionalities locally on your computer.
- Need a remote database to service your web app.
- Need a free database for minimal usage.
If you tick all these boxes, then let's get started.
WHY DO YOU NEED AN ONLINE DATABASE
The question most people ask is:
Why can't I utilize the same database used during development for deployment?
The truth is, only you have access to your local database and can only access it from your computer. Therefore, for other people to use your web application, you need something hosted and accessible by everyone. As of the time of writing, all databases mentioned here are free of charge. Although some require you to save your credit card details, should you need to scale your usage? But no worries, your little side project will not exceed the free allocations.
HOSTING PLATFORM
Since Heroku is one of the most popular and developer-friendly hosting solutions out there, the examples provided in this article will focus on utilizing these databases on Heroku. If you are new to Heroku, check out their concise instructions on how to get started before you continue.
THE OPTIONS
Since your web application will probably use either an SQL or NoSQL database, we will consider the most popular options for both databases.
- MongoDB for NoSQL with NodeJs.
- PostgreSQL for SQL with Python.
MongoDB Atlas
MongoDB offers an easy-to-set-up online database solution that you can connect to your web application within minutes. Follow these steps to set up your MongoDB database with Heroku.
CREATING A CLUSTER
You need to have an account with them, so head over here to create an account.
Upon successfully creating an account, you will need to create a starter cluster. Meaning you need to have a database instance before you can start using MongoDB. You will be required to select one option from the following fields:
- Cloud Provider & Region: Since our preferred platform for deployment is Heroku, the best choice is AWS and N.Virginia. The option has to do with Heroku hosting their servers on AWS.
- Cluster Tier: This concerns what size of storage you will prefer to utilize. The MO Sandbox 512GB will work just fine for our side project.
- Additional Settings: The MongoDB 4.4 No Backup Version option is also suitable for our use case.
- Cluster Name: This is the name of the cluster, and you have the liberty of choosing whatever cool name you like. An option will be the project's name. Note that you can not change the name of the cluster after setting it up.
Verify that all options are correct, then click on the "Create Cluster" button to create your very first cluster!. Please note that this process for the first time takes a couple of minutes.
CREATING A DATABASE USER
Next, we have to create a name and password authorization so that our database has some security. For this, we head over to Database Access on the left navigation bar. By clicking "Create a new Database User." a box inquiring about the necessary details to set up username and password is shown on the screen.
For this article, the preferred role for the user should be "Atlas Admin.". Finally, click on "Add new User." That is it, the process of creating our database cluster is successful.
AUTHORIZING AN IP ADDRESS
Before connecting our new database to our web application, we only need to perform some more simples steps. MongoDB requires us to provide an authorized IP address that will be able to access our database. See this as another layer of security to protect your database from unauthorized access. On the same left navigation bar, select the Network Access option. There will now be an option to add an IP Address. Clicking the Add IP Address option prompts to whitelist an IP address. For this article, all IP addresses will be allowed. Select the "Allow access from anywhere option." and confirm to save.
CREATING A DATABASE COLLECTION
If you are familiar with MongoDB, you already know what a collection is, but in case you aren't, collections are groupings of MongoDB documents. They represent a table if you are coming from a relational database background. They contain all our different MongoDB documents. Still confused, then check this out to get a grasp of our MongoDB works. Follow these steps to create your first database collection:
- On the left navigation bar, click on "Clusters." Select the cluster you created earlier.
- A screen with several options appears. Select "Collections."
Click on "Create Database" and fill in the two options:
- Database Name: This should be the name of the database that will contain all collections for the app
- Collection Name: This is specific to the use of that collection. A database with the name "library" might have books, students, and staff collection separately.
Click on create to save the database.
Whew!! that was tasking. Hopefully, everything went well, and we now have a fully functional database that can integrate with any of our deployed web applications.
CONNECTING TO OUR HEROKU WEB APP
The whole point of creating an online cluster is to utilize it in our deployed web application, so let us connect our new database. To do this, we need three things:
- the connection string for the new database.
- a Heroku environment variable that points to this connection string.
- Instruct our app to use either the connection string or our local MongoDB.
CONNECTION STRING
To connect the new database, we need a connection string that points to it. Head over to the database cluster dashboard, do this by clicking the Clusters option on the left navigation bar.
On the far right, click the Connect option and choose the "connect your application.". The default option for Driver is the NodeJs, which you can change depending on your stack. Copy the connection string below and head over to the next step.
Depending on your name, the connection string should look like this: "mongodb+srv://yourUsername:yourPassword@yourClusterName.n9z04.mongodb.netyourDatabase?retryWrites=true&w=majority"
Heroku automatically inserts your username and cluster name, but you will need to replace the "yourpassword" field with the password you chose when setting up the database User account.
HEROKU ENVIRONMENT VARIABLE
Next, we have to set an environment variable in Heroku that saves our connection string in the deployment environment. The importance of this is to avoid hard coding our sensitive information into our web application. There are two options :
- Using Heroku command-line tool: We create a variable called DB_URL by running the comman below in the Heroku CLI. Before this step, you should go through this .
heroku config:set DB_URL= [our connection string]
Before you paste your connection string, a good practice is to:
- paste it in your note editor
- Replace the field with your Database Admin password you set up earlier.
For example, after editing your connection string, it should look like this:
For a MongoDB account withmongodb+srv://jane:janedoe@libraryapp.n9z04.mongodb.net/books?retryWrites=true&w=majority"
- username = jane
- password = janedoe
- cluster name = libraryapp
- collection name = books
Copy the edited version of the connection string and paste. Therefore for the Heroku CLI config. We run:
heroku config:set DB_URL = "mongodb+srv://jane:janedoe@libraryapp.n9z04.mongodb.net/books?retryWrites=true&w=majority"
If you are not too comfortable with the Heroku CLI, then you can add environment variables by following these steps:
- Log in to your Heroku account in your browser.
- Head to your dashboard.
- Select the app you want to add MongoDB database.
- Click on settings and scroll down to Config vars.
- Add a new config var with:
- KEY = DB_URL
- VALUE = [the edited connection string]
And that is it your database should now fine. Oh wait, one more thing, we have to configure our app itself to use this new URL.
ADDING DUAL DATABASE FUNCTIONALITY TO APP
The last thing to do is add this Heroku config var to our app to use.
Your database design might differ, but this implementation is the same,
- Get the DB_URL variable in your app by running
remoteURL = process.env.DB_URL
- add it as an optional value passed to mongoose (if you are using the popular MongoDB ODM). by running
Here is a simple web application that shows how you can put everything together. Feel free to check it out.mongoose.connect(remoteURL||localURL, options);
Voila, we now have a fully functional web application that works well in local development, and when hosted on Heroku. have any questions? Email me, and I will get back as soon as possible. As promised, next time, we will be considering the option for PostgreSQL. Till then, happy hacking.