Transformed the Next.js Pages Router into an Application Router

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.

Answer №1

This response pertains to the query: "How can I put this into practice?"

  1. Distinguish between "Page Route" and "App Route"

In a Page route, you are expected to have one function handler for an endpoint irrespective of the method.

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

For App routes, multiple functions are required with each mapped to a specific method.

function GET(request: Request) {}
function POST() {}
  1. Select the appropriate option

Immediately at the outset, you encounter

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

This indicates that you should handle the GET method exclusively.

Simply transfer the remaining code from your handler function into the GET function

function GET(request: Request) {
    // rest of the code
}
  1. Rectify the distinctions between NextApiRequest in page routes and Request in app routes

Refer to StackOverflow again on how to extract the query from the Request object in App Routes of Next 13.

  1. Resolve the disparities between NextApiResponse in page routes and Reponse in app routes

Consult the official documentation https://nextjs.org/docs/app/building-your-application/routing/route-handlers

The GET function expects a return of Response.

The process will be quite similar.

If any discrepancies arise, search for solutions on StackOverflow related to those specific mismatches.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angulajs: The correct way to simulate a Promise received from $http

Seeking guidance after struggling with unit testing an angular service, specifically the failed part of a promise. (function () { angular.module('testable') .factory('myService', ["$http", "$q", function ($http, $q) { retur ...

The chosen index in the Material Stepper feature is experiencing a malfunction

I've been busy working on a Mat-Stepper, actually two of them. I have a component that contains two ng-templates set up like this: Question: Why is my selected index not functioning as expected? Am I missing something? I know you can define [selected ...

JavaScript code to alter the timeout duration for image changes: Update

I am working on a fun project that involves alternating between two images, one green and the other black. Here is the code snippet: <script> var switchImage = 1; var delayTime = 500; switchImages() function switchImages() { if (switchImage == 1) ...

Tips for passing props while clicking on a v-data-table:

I am currently facing an issue in my app while using v-data-table. I am able to pass props with an extra slot, but I want the entire row to be clickable in order to open a dialog with the prop item: <template v-slot:item.actions="{ item }"> ...

What is the significance of the A tag when parsing a URL?

So, I encountered a problem that involved parsing a URL to extract the hostname and pathname, then comparing the extracted pathname with a string. If you need help with this issue, check out this post: How do I parse a URL into hostname and path in javasc ...

Retrieving checkbox list values using jQuery

I am working with a div that contains some checkboxes. I want to write code so that when a button is clicked, it will retrieve the names of all the checked checkboxes. Can you provide guidance on how to achieve this? <div id="MyDiv"> .... <td> ...

What is the best way to initiate my project using the .next directory?

Looking to kick off my NextJS project directly from the build folder (.next). I've already run the next build command and have the .next folder ready. However, despite numerous attempts and different methods, I haven't been able to successfully s ...

What is the most effective way to transfer visitor hits information from an Express.js server to Next.js?

I've developed a basic next.js application with an express.js backend. What I'm aiming for is to have the server track hits every time a user visits the site and then send this hit count back to the next.js application. Check out my server.js cod ...

Implementing ISR for static routing fallback in Next.js

When it comes to enabling ISR with fallback, I understand that exporting getStaticPaths in the page is necessary: export const getStaticPaths = () => { return { paths: [] , fallback: 'blocking' } } However, getStaticPaths only works ...

No data being fetched through Ajax

I am facing an issue with retrieving PHP data in the form of an array. I have created an AJAX query to display data in two divs: one is a drop-down and the second is where all data will be shown. However, the problem is that when I attempt to do this, all ...

Autocomplete Data Origin

I'm currently exploring the use of Typeahead and implementing AJAX to fetch my data source: $(document).ready(function() { $('input.typeahead').typeahead( { hint: true, highlight: true, m ...

React Router Error: Hook call invalid. Remember to only use hooks inside the body of a function component

I am having an issue with my React app that uses react router. In Box.js, I am attempting to access the URL parameters but I am encountering the following error message: Invalid hook call. Hooks can only be called inside of the body of a function component ...

Guide to Embedding Dynamic Images in HTML Using VUE

I am venturing into the world of VUE for the first time, and I find myself in need of a header component that can display an image based on a string variable. Despite my best efforts to search for tutorials, I have not been able to find a solution. Header ...

Having trouble running classes using Maven test with the Testng.xml file in the terminal, however, it runs smoothly in Eclipse

While I have been successful in running my solution through the testng suit in the Eclipse console, I am facing difficulties executing the testng.xml file via Maven integrated with Sauce Labs in the terminal. Output received on the terminal: ------------ ...

Leveraging shadow components with the Next.js pages directory

I am facing an issue with getting a simple shadcn button to work because I am unable to import the button. Although I am using nextjs 13, I am still utilizing the pages directory. Below is the process of how I installed shadcn. Here is the installation co ...

Exploring the wonders of Onsen UI's ng-repeat feature combined

Facing a major issue with my app, and I suspect it's due to the asynchronous call. The HTML section looks like this: <ons-list ng-repeat="item in newsEventi.items"> <ons-list-header class="news_titolo_lista">{{item.categoria}}</ons ...

What could be causing the lack of Tailwind CSS intellisense in a Next.js app with TypeScript?

Check out my tailwind.config.ts file I've been trying to figure it out by watching YouTube tutorials, but nothing seems to be working. Even with the tailwind.config.ts file in my Next.js app, it still isn't functioning properly. Perhaps there&ap ...

Alert users before visiting external websites

Is there a way to notify users about external pages without using popups like in the first example here: Instead of the unwanted code shown above, is there an alternative solution? Is there a different approach that can be taken? For instance, check out ...

Transform objects into arrays

Is there a way to transform an object into an array of objects while adding new keys and values? This is my current object: { "0": "Ann_B", "1": "Billy_P", "2": "Carly_C", "3": "David_L" } I would like it to look like this: [ { "value": "Ann_B ...

Arranging a string array in JavaScript according to an integer array

Looking at the provided javascript arrays: letterArray ['a', 'e', 'i', 'o', 'u'] We also have another array that corresponds to it: valueArray [12, 22, 7, 7, 3] The goal is to sort the valueArray into: ...