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

Lee Robinson

Lee Robinson / February 04, 2020

2 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.

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 access token for your new application.

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

Creating an environment variable

To securely access the API, we need to include the access token with each request. We also do not want to commit this value to git, so let's use an environment variable.

Since I'm deploying with Vercel, I can add the environment variable with the CLI.

$ vercel env add unsplash-access-token <value>

To use it when running locally, add it to your .env (or .env.local) file.

UNSPLASH_ACCESS_TOKEN=<value>

We can now reference the value 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.

We want to pull statistics for a given user and return the total number of downloads and views. We can use the Unsplash API to retrieve this information.

Bonus: We can cache the API Route with the cache-control header.

export default async function handler(req, res) {
  const accessToken = process.env.UNSPLASH_ACCESS_KEY;
  const response = await fetch(
    `https://api.unsplash.com/users/leerob/statistics?client_id=${accessToken}`,
    {
      method: 'GET'
    }
  );

  const unsplashdata = await response.json();

  res.setHeader(
    'Cache-Control',
    'public, s-maxage=1200, stale-while-revalidate=600'
  );

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

Example

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

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.

- subscribers – View all issues