Base64 Encoding

While browsing some API documentation, I saw references to Base64 for passing credentials to the API. I had seen Base64 referenced a few times, but had no idea how to convert text into Base64. So, I did some digging. This post will outline how to encode (and decode) text into Base64 using the MacOS Terminal.

What is Base64?

I should share a little bit about what base64 is. The MDN documentation explains the overarching concept of Base64 is.

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation.

You can think of Base64 is another way to represent binary or text data.

The conversion process is somewhat detailed, and I encourage you to check out the resources at the bottom of this article if you are curious about the benefits and technical details of Base64.

Converting Text into Base64

While reading those API docs, I had no idea to create a Base64 string.

There are converters a few Google searches away. But, did you know there’s a Base64 command built into the MacOS?

To turn a string into Base64, open a new Terminal window, and use this format.

base64 <<< string

That would be base64 followed by a space, three less-than signs (<), another space, then whatever string you want to encode in Base64.

Here’s an example:

If I wanted to convert the string I love cheeseburgers into Base64, I would enter this:

base64 <<< "I love cheeseburgers"

Which would print out SSBsb3ZlIGNoZWVzZWJ1cmdlcnMK as a result.

You only need quote marks around the string you would like to convert, if it has space it in.

The following does not need quote marks, for example:

base64 <<< ilovecheeseburgers

Decoding Base64

With a similar command, you can decode Base64 back into human, readable text.

Let’s say a friend of ours sent us the following code:

SSBsb3ZlIHlvdSBtb3JlCg==

To decode Base64, we add a -D flag before the three arrows and after base64.

Like this:

base64 -D <<< SSBsb3ZlIHlvdSBtb3JlCg==

Which returns I love you more. How sweet!

Base64 is Not Unique

While a Base64 string like SSBsb3ZlIGNoZWVzZWJ1cmdlcnMk looks random, it is not.

Each time I run base64 <<< "I love cheeseburgers" it’ll return the same result. If you run the same code, you’ll get the same result. And since a Base64 string can be decoded, it’s not appropriate for hashing passwords, storing API keys, etc.

Resources

Planning Your Escape from Tutorial Hell

I’ve previously written about doing tutorial based projects and how it’s not a bad thing.

What can happen, is that your project looks like everyone else’s who did the same tutorial.

Again, this is not a bad thing.

But you can take your learning a step further by adding features onto those projects.

Here are some ideas to get you started

Automation

  • Automatically deploy changes each time a git repo is updated

CRUD operations

  • If a user can create items as part of your project, can they edit them as well?

Deploy

  • Migrate your backend database to Postgres and host on Heroku.
  • Automatically deploy your frontend to Netlify or Vercel.

Error handling

  • What happens if a user tries to navigate away from a page while they were filling out a form field?
  • What if there is no result from an API query?

Form validation

  • Are there any form fields are required or nullable?
  • What happens if a user enters a string when a field is only meant to access numbers?

oAuth

  • Give users the ability to login with Google, Facebook, etc

Offline access

  • What does a user see if there is a slow connection? Do they see a blank screen or some content?
  • Store changes in the browser with a service worker until database access is restored

Permissions

  • If a user is logged in, should they be able to view assets created by another user?

Refactor

  • Take a look at your code and see if there are opportunities to DRY it up.
  • Incorporate arrow functions, swap var instances for let or const, incorporate asynchronous functions.
  • Remove console.log(), debug() and TODO comments from deployed code.

Styling

  • Better rendering for mobile, dark/light mode toggle, make sure it’s accessible, etc.

Security

  • Are there any risks of exposed API keys or sensitive user data?
  • Is CORS enabled?

Tests

  • Write test to validate functions are outputting the expected results.

Free APIs

I’m a little obsessed with APIs.

They are fun to work with, especially for personal projects.

Here’s a list of fun, free, publically available API’s that I’ve been eyeing for potential new projects.


  • Bread Pun API – API for all your wholewheat bread bun kneads.
  • TheCocktailDB – An open, crowd-sourced database of drinks and cocktails from around the world.
  • Deck of Cards – An API where you can query, shuffle and deal decks of cards.
  • Dog API – The internet’s biggest collection of open source dog pictures.
  • Foursquare Places API – Get flexible access to global POI data and rich content from over 100K trusted sources and driven by millions of consumers.
  • GIPHY API – Ready to bring the engaging power of GIFs to your app through GIPHY?
  • NASA APIs – Multiple APIs available for use, including Mars Rover Photos.
  • OMDb API – The Open Movie Database (OMDb) API is a RESTful web service to obtain movie information, all content and images on the site are contributed and maintained by our users.
  • Open Emoji API – A free emoji API sourced directly from unicode.org – always up to date. _Currently under development._
  • PokéAPI – All the Pokémon data you’ll ever need in one place, easily accessible through a modern RESTful API.
  • STAPI – A Star Trek API. It’s an open source project, that anyone can contribute to.
  • SWAPI – The Star Wars API
  • Tropical Fruit and Veg – The tropicalfruitandveg.com API provides a quick simple way to integrate information on tropicalfruitandveg.com within your own website or within a mobile application.

API Aggregate Websites

I cannot vouch for the APIs listed on these sites, but they are worth browsing if you are looking for something specific or interesting.

  • API List – A collective list of APIs.
  • Rapid API – Free Public APIs for Developers APIs

Open Graph for Personal Projects

A way to make your posts stand out on social media is to include images. According to Buffer, Tweets with images can get up to 150% more retweets. So it makes sense to include some kind of visual element instead of dropping a link and calling it a day.

For a long time, I wondered how some links I would share would automatically get nicely formatted images, headlines and links. Was it possible to implement something like that on my projects so that I automate and improve the link-sharing experience?

Yes!

This functionality can be implemented using The Open Graph protocol.

I’ll walk through how I step it up on one of my projects.

Implementing Open Graph

The introduction says it well. In describing the Open Graph protocol, it says:

The Open Graph protocol enables any web page to become a rich object in a social graph.

The graph it refers to is an object that is created by including basic metadata tags in your webpage.

Your website most probably has metadata tags like <meta charset="UTF-8"> or <meta name="viewport" content="width=device-width, initial-scale=1.0">. The Open Graph tags use the same, self-closing <meta /> tag structure with some additions. Each Open Graph meta tag has a property and content attributes. The property attribute, describes or categorizes the value in the content attribute.

For Open Graph to work, there are 4 required properties for each webpage.

Those properties are:

  1. og:title
  2. og:type
  3. og:image
  4. og:url

Detailed descriptions of these tags can be found in the Basic Metadata section of the documentation. But, they make up the core elements of those media-rich posts that we see on our Twitter and Facebook feeds.
Using my Halloweenti.me project as an example, my 4 meta tags look something like this.

<meta property="og:title" content="How Many Days Until Halloween?" />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://halloweenti.me/" />
<meta property="og:image" content="https://halloweenti.me/my-image.jpg" />


Once my HTML file is pushed live, sharing the link to halloweenti.me automatically renders the image that I specified along with a title and URL to the website.

Looking Nice

Prior to adding Open Graph, sharing the https://halloweenti.me/ link in Discord looked like this.

An example of what the URL looks like without The Open Graph protocols

I mean, I think this site it awesome, but it’s probably not grabbing anyone else’s attention.

This is how it looks now.

How the URL looks after including an image that I specified, title and description.

Wow! That is easier to see and gives more context to a user who is just scrolling by. You can also see how the 4 required properties show up in the social media preview.

Conclusion

What I like about The Open Graph Protocol is that it’s relatively easy to implement and there are additional meta tags that can be added for richer content examples. I included a description for my project, but there are tags that are relevent for dated content like blog posts are articles.

I reccomend giving The Open Graph protocol a try so that your projects can better stand out on social media.

Resources

Count How Many Days Until Halloween with Javascript Date Objects

I’ve had fun making updates to my Halloweenti.me project this October.

I made the decision not to make it an open source or Hacktoberfest eligible project this year. But, I’ve enjoyed making upgrades and trying new things.

When I refreshed this project in early October, I knew that my current logic did not account for if Halloween had already passed for that calendar year. In the afternoon of the spookiest day of the year, I’ve found a solution that works!

Here’s how I did it.

What is the Problem?

I’ve previously written about date objects in Javascript, but as a refresher, here’s the code that I started with.

const now = new Date()
const halloween = new Date(`October 31, ${now.getFullYear()} 00:00:00`)
const timeUntil = halloween.getTime() - now.getTime()
const daysUntil = Math.abs(Math.ceil(timeUntil / (1000 * 60 * 60 * 24)))

Here’s a line by line breakdown of what’s happening.

  1. A new date object is being created based off the current date and time.
  2. A second date object is created with the value of October 31st, of the current year (which is referenced from the first date object).
  3. The time of the first object, is subtracted from the time of the second object. The result is is milliseconds.
  4. The milliseconds from the above line is converted into days by
    1. Dividing it by 1000 * 60 * 60 * 24.
    2. Rounding the result down to the nearest integer
    3. Returning the absolute value (meaning, removing the negative, if the result if a negative number)

If today’s date was October 1st, 2020, this is what each line would return.

const now = new Date() // Thu Oct 01 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
const halloween = new Date(`October 31, ${now.getFullYear()} 00:00:00`) // Sat Oct 31 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
const timeUntil = halloween.getTime() - now.getTime() // 2592000000
const daysUntil = Math.abs(Math.ceil(timeUntil / (1000 * 60 * 60 * 24))) // 30

Counting on our fingers, from the 1st of October to the 31st, 30 days to Halloween would be correct.

Where it gets weird is when Halloween has passed for this calendar year.

Let’s pretend it’s the day after Halloween (November 1st, 2020).

const now = new Date() // Sun Nov 01 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
const halloween = new Date(`October 31, ${now.getFullYear()} 00:00:00`) // Sat Oct 31 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
const timeUntil = halloween.getTime() - now.getTime() // -86400000
const daysUntil = Math.abs(Math.ceil(timeUntil / (1000 * 60 * 60 * 24))) // 1

Our daysUntil variable returns 1, as in “There is 1 day until Halloween” which is not right. Better wording would be “It’s been 1 day since Halloween” but not what I am going for. This is meant to be countdown to Halloween, so I needed to find another way.

Solution

I tried reworking the timeUntil and daysUntil functions, when really I needed to think about the relation between the now date object and the halloween date object.

If I was always referencing the current year to create the halloween date object it would never look ahead to next year. So, I needed to increment the year that I pass into the date object by 1 (as in, next year) only if Halloween had already happened in this calendar year.

How can I do that?

Well, after Halloween there are only two months left in the calendar year. So, if the current month—the month in the now date object—was greater than the month that Halloween falls in, create a halloween object using next calendar year.

Date objects have a built in getMonth() function, which return an integer. Since the months of the year are zero indexed, January would return a 0, February would return 1 and October would return 9.

If it’s November or December, the result of getMonth() on the now object would be 10 and 11 respectively.

Knowing that, I can add some conditional logic before the halloween object is created.

...
const now = new Date()
let year = now.getFullYear()

if (now.getMonth() > 9) { year += 1 }

const halloween = new Date(`October 31, ${year} 00:00:00`)
...

Let’s pretend it’s November 1st again. Here’s what our updated code would return.

const now = new Date(`November 1, 2020, 00:00:00`) // Sun Nov 01 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
let year = now.getFullYear() // 2020
if (now.getMonth() > 9) { year += 1 }
const halloween = new Date(`October 31, ${year} 00:00:00`) // Sun Oct 31 2021 00:00:00 GMT-0400 (Eastern Daylight Time)
const timeUntil = halloween.getTime() - now.getTime() // 31449600000
const daysUntil = Math.abs(Math.ceil(timeUntil / (1000 * 60 * 60 * 24))) // 364


364 days until next Halloween is right! I can double check that my logic works by pretending it’s the the first of the year.

const now = new Date(`January 1, 2021, 00:00:00`) // Fri Jan 01 2021 00:00:00 GMT-0500 (Eastern Standard Time)
let year = now.getFullYear() // 2021
if (now.getMonth() > 9) { year += 1 }
const halloween = new Date(`October 31, ${year} 00:00:00`) // Sun Oct 31 2021 00:00:00 GMT-0400 (Eastern Daylight Time)
const timeUntil = halloween.getTime() - now.getTime() // 26175600000
const daysUntil = Math.abs(Math.ceil(timeUntil / (1000 * 60 * 60 * 24))) // 303

A Google search of how many days between January 1 2021 and October 31 2021. confirms this too.

Google search result showing 303 days between January 1st and October 31st 2021

The Finished Product

Ahhhhh! The working code for the Halloween countdown can be seen at Halloweenti.me.

As of right now, October 31st, 2020, you’ll see a gentle reminder to have fun and celebrate safely.

Halloweenti.me website with the text “Today is Halloween! Eat, drink and be scary!”

With the value of the current date object (now) in relation to Halloween, the text displayed on the webpage is updated. It will reflect how many days until Halloween and specific messaging if Halloween is today or tomorrow.

Resources