hoangvvo / next-connect

The TypeScript-ready, minimal router and middleware layer for Next.js, Micro, Vercel, or Node.js http/http2
https://www.npmjs.com/package/next-connect
MIT License
1.62k stars 65 forks source link

fetch remote image with cors #242

Open janwagner opened 5 months ago

janwagner commented 5 months ago

Hi.

I am trying to use next-connect to load images from a remote host. I am relatively new to next.js api routes and would be very grateful for any help.

Has anyone ever tried something similar, is it even possible to retrieve an image this way and thus to handle cross-origin requests?

My goal is to either have the image as a blob in the end, or directly convert it directly to base64

pages/api/image.ts
import { createRouter } from 'next-connect'
import cors from 'cors'
import type { NextApiRequest, NextApiResponse } from 'next'

const image = 'http://placekitten.com/g/1000/1000'

const router = createRouter<NextApiRequest, NextApiResponse>()
  .use(cors())
  .get(async (req, res) => {
    const response = await fetch(image)
    const data = response.blob

    res.json(data)
  })

export default router.handler()