Create a Dashboard with Next.js API Routes - Unsplash API

LR

Lee Robinson / February 04, 2020

3 min read––– views

In this series, you will learn how to create a dashboard using Next.js API routes and integrate with third-party APIs.

Unsplash Downloads

-

Overview#

Unsplash is the largest source of high-quality images on the internet. Amateur and professional photographers give back by allowing their photos to be used 100% free for commercial and non-commercial usage.

They also provide a fantastic API, which gives you access to millions of photographs and a variety of metrics. As an Unsplash contributor, I wanted to see how many times my photos have been viewed and downloaded.

Getting Access to Unsplash#

To gain access to the Unsplash API, you need to:

  • Create an account.
  • Go to your applications.
  • Click “New Application.”
  • Accept the terms of usage.
  • Fill in the required details.
  • Retrieve the secret key for your new application.

That's it! 🎉 You now have access to make requests to the Unsplash API with your secret key.

Creating an Environment Variable#

To securely access the API, we need to include the secret with each request. We also do not want to commit secrets to git. Thus, we should use an environment variable.

Since I'm deploying via Now, I can add the secret via their CLI.

$ now secret add unsplash-access-token

To reference it locally when using now dev it needs to be added to your .env file.

UNSPLASH_ACCESS_TOKEN=042d344

Finally, we need to add our new secret to now.json.

{
  "env": {
    "UNSPLASH_ACCESS_KEY": "@unsplash-access-key"
  }
}

We can now reference the secret via process.env.UNSPLASH_ACCESS_KEY in our API route.

Creating the API Route#

Let's start by creating a new API route at pages/api/unsplash.js.

export default (req, res) => {
  return res.status(200).json({});
};

To make server-side requests to Unsplash, we can install the unsplash-js library. Since the library depends on fetch, you need to include isomorphic-unfetch (or another fetching library like node-fetch).

$ yarn add unsplash-js isomorphic-unfetch

Then, we can initialize unsplash-js inside our API route.

import fetch from 'isomorphic-unfetch';
import Unsplash, { toJson } from 'unsplash-js';

let unsplash;

export default async (_, res) => {
  if (!unsplash) {
    unsplash = new Unsplash({
      accessKey: process.env.UNSPLASH_ACCESS_KEY
    });
  }

  return res.status(200).json({});
};

Finally, we want to pull statistics for a given user and return the total number of downloads and views.

import fetch from 'isomorphic-unfetch';
import Unsplash, { toJson } from 'unsplash-js';

let unsplash;

export default async (_, res) => {
  if (!unsplash) {
    unsplash = new Unsplash({
      accessKey: process.env.UNSPLASH_ACCESS_KEY
    });
  }

  const userStats = await unsplash.users.statistics('leerob');
  const { downloads, views } = await toJson(userStats);

  return res.status(200).json({
    downloads: downloads.total,
    views: views.total
  });
};

Example#

The two cards below talk to /api/unsplash and pull back stats about my Unsplash account.

Bonus: You can cache the API route with the cache-control header.

Cache-Control: public, max-age=120, stale-while-revalidate=60

Keep Reading#

Create a Dashboard with Next.js API Routes

Subscribe to the newsletter

Get emails from me about web development, tech, and early access to new articles.