Looking to make a change in my API written with Nextjs's Pages Router. Currently, it serves as a proxy for downloads and I am interested in converting it to the App Router method. Does anyone have any guidance on how to go about implementing this?
import axios from 'axios'
import type { NextApiRequest, NextApiResponse } from 'next'
type TQuery = { url: string; name?: string }
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'GET') return res.status(404).end()
const { url, name } = req.query as TQuery
if (!url) return res.status(500).end()
try {
const filename = name || url.split('/').pop()
const controller = new AbortController()
const response = await axios.get(url, { responseType: 'stream', signal: controller.signal })
res.setHeader('Content-Type', 'application/octet-stream')
res.setHeader('Content-Disposition', `attachment; filename=${filename}`)
response.data.pipe(res)
const close = () => {
response.data.destroy()
controller.abort()
}
res.on('close', () => close())
res.on('error', () => close())
} catch (error) {
res.redirect(url)
}
}
An example demonstrating the conversion to App Router would be greatly appreciated.