How to display a random cute animal on a 404 page

As I slowly start piecing together this site, there are plenty of broken links floating about. After the homepage itself, the page I'm seeing the most is the Error 404 Page Not Found page.

I hope by the time you're reading this, it will be a much less frequent occurrence but I thought I'd follow a long tradition of custom 404 pages and add my own. Hitting a 404 is usually an unpleasant experience so I'll try and balance that out with a pleasant one - and what does everyone love? Cute animals of course!

Nawww....look at them!

So why not load a random picture of a cute animal when someone hits a 404 Error? This site is built with Gatsby which makes creating a custom 404 page very straightforward - it just loads whatever is at src/pages/404.js. Your page may deal with it differently. The good thing is regardless of what's made to build your page, as long as it can hit the internet (and all the best websites can) getting these random images is super simple.

We're going to use the ever amazing Unsplash for our images. Why? Because they're free! More specifically we're going to use their API Unsplash Source. They have a more advanced API available, but we don't need it for this.

If we wanted to get any random image we can simply visit https://source.unsplash.com/random.  We don't want any random image though - we want our cute animals! Fortunately Unsplash makes this easy for us.

https://source.unsplash.com/640x480?cute-animals

You can see our keyword on the end of that link. You can add multiple terms if you want by separating with a comma, but we'll keep it simple. We don't need to give our visitors a huge full resolution file for a little fun like this, so we should add some height and width dimensions so the Unsplash CDN gives us a nice manageable size.

We're nearly there. All we need to do is add this link where we would normally add a link to an image. This can be with a CSS background image:

background-image: url("https://source.unsplash.com/640x480?cute-animals");

A good old HTML img tag:

<img src="https://source.unsplash.com/640x480?cute-animals"></img>

Or however else you want to consume the URL! Don't forget the purpose of the 404 page - to tell the user something has gone wrong and provide them with a link back to your actual content.

That's it! You can check out the full Unsplash API for more advanced ideas. What ideas can you come up with? This is a simple one but maybe it can put a smile on someone's face. At the very least, when something's gone wrong on this site, it'll put one on mine.