0

This is an API written using Nextjs's Pages Router. The function is to proxy downloads. Now I want to convert it to the App Router method. How can I implement it?

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)
  }
}

I wish there was an example of App Router conversion.

1 Answer 1

2

This answer is for your question: "How can I implement it?"

  1. Identify the different between "Page Route" and "App Route"

Page route: expects you have 1 single function handler for an endpoint name no matter what method is.

function handler(req: NextApiRequest, res: NextApiResponse) {}

App route: expects you have multiple function. Each one mapped to a single method

function GET(request: Request) {}
function POST() {}
  1. Pick the corresponding one

Lucky for you right at the beginning you have

if (req.method !== 'GET') return res.status(404).end()

This means you are expected to handle GET method only

So just copy the rest of your handler function into the GET function

function GET(request: Request) {
    // the rest of the code
}
  1. Fix the differences of NextApiRequest of page route and Request of app route

Now search StackOverflow again for how to get query from Request object of App Route of Next 13.

  1. Fix the differences of NextApiResponse of page route and Reponse of app route

Check offical document https://nextjs.org/docs/app/building-your-application/routing/route-handlers

the GET function expect to have Response return.

Thing will be nearly identical.

If something mismatch, search StackOverflow again for that specific mismatching.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.