Toms Tech Blog

Next.js API routes with external api calls

July 11, 2020

Example of an API route in pages/api/swapi.js:

import axios from "axios"

export default async (req, res) => {
  const url = ``

  await axios
    .then(({ data }) => {
      res.status(200).json({ data })
    .catch(({ err }) => {
      res.status(400).json({ err })

Example of a reusable hook with swr to call your api route. This hook can then be used in your Next.js pages:

import useSWR from "swr"

const fetcher = url => fetch(url).then(res => res.json())

export function useSwapi() {
  const { data, error } = useSWR(`/api/swapi`, fetcher)

  return {
    data: data,
    isLoading: !error && !data,
    isError: error,

Why not calling the swapi api directly from the client? In this case that would be perfectly OK. However, I use api routes this way when I need to add extra info to the external api call, like an authorization header.

Written by Tom, freelance front-end web developer in the greater Amsterdam area. Read my Tech blog. Or hire me.