iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🏙

Creating an Image Proxy API using Next.js API Routes

に公開

:::message warn
While the methods introduced in this article are usable with Next.js, there may be limitations or policies depending on the service you use.
If you are using Vercel, it is recommended to check their Fair Use Policy.
:::

A proxy function is something you occasionally need for tasks like bypassing CORS.
In Netlify, this could be achieved with a proxy, but when using Next.js in other environments, using the API routes functionality seems to be a good approach.

// /api/img.js
import axios from "axios"

export default async (req, res) => {
  try {
    const r = await axios.get(req.query.url, {
      responseType: "arraybuffer",
    })
    res.end(r.data)
  } catch (e) {
    res.end(500)
  }
}

It's easy to set up with just this.

For example, if you want to extend it to include resizing or to forward headers, it would look something like this:

import axios from "axios"
import sharp from "sharp"

export default async (req, res) => {
  try {
    const r = await axios.get(req.query.url, {
      responseType: "arraybuffer",
    })
    const buf = r.data
    // resize
    const item = await sharp(buf).resize(800).toBuffer()

    // forward headers
    Object.entries(r.headers).map(([k, v]) => {
      res.setHeader(k, v)
    })
    res.end(item)
  } catch (e) {
    res.end(500)
  }
}

Discussion