Using Connection Strings to Connect to Cloud Services

Unless a website is static, it almost certainly connects to other cloud services such as databases or caches that are hosted on servers other than the ones on which main application is running. Connection strings are used to identify where to find the server running the service, what type of driver to use (Postgres, Redis, AMQP, etc.), and what credentials to access it with.

At first glance, they can look like nonsense and be difficult to parse, but the good news is, there’s a logic behind it all! Regardless of the service you’re using it to connect to, they all follow the same pattern:

driver://<username>:<password>@<server>:<port>/<database name>

I have a database on my local machine that I can connect to using this as my connection string:

postgres://adriennedomingus:@localhost:5432/test_database

You’ll notice there’s no password there — if a particular piece of the connection string is not relevant, it can be left blank, but the connectors must still be included (the : after adriennedomingus is there, even though it’s immediately followed by the @ sign). The port could also be left off in this example, since 5432 is the default port for Postgres.

Something like this might look more familiar, as this is what a connection string would look like for a service hosted in the cloud, instead of on my local machine (All these strings are randomly generated, don’t get any ideas that this will connect you to a real database 🕵🏻‍♀️):

postgres://80leaokcsq476w:mt3auwvuijzqhvaacyte4w6exehzxqlk3skautpid2thfxynj0@ec2-93-402-35-72.compute-1.amazonaws.com:5432/pz794zs8x2twme

Connection strings should be treated like passwords. After all, one of the sections of a connection string is in fact a password! If someone has access to a connection string, they have the ability to perform any actions on the service that the user has.

For example, my local database string above has the username adriennedomingus - if that user had been granted read-only permissions, anyone with the string can access the database with the same permissions. Likewise, if that user had full admin access to the Postgres instance, someone with that string could perform any operation on the database they wanted, including reads, writes, schema updates, or even deletion!

For this reason, they should be treated the same way as other secret or encryption keys used by your application, and not checked into source code.