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

Infinite scrolling made effortless with jQuery and Ajax

I am attempting to create a basic infinite scroll feature that monitors when the user scrolls to the bottom in an HTML file. Once the bottom is reached, it should then load additional content from another HTML file which contains more text. The second HTM ...

using Javascript to eliminate necessary tags from concealed tabs

My goal is to dynamically remove the required tag from fields in hidden tabs when a tab is clicked using JavaScript. The presence of the required tag on unused fields causes issues with form submission, preventing data insertion into the database. Here&apo ...

An unexpected 'u' token was encountered in the JSON data at the beginning while parsing with NextJS from the router.query

I have successfully passed data through the URL path from my main page to my quotes page component in NextJS 13. However, I encountered an error when trying to refresh the page. Quotes Page Component import React from 'react' import { useRouter ...

Issue when trying to use both the name and value attributes in an input field simultaneously

When the attribute "name" is omitted, the value specified in "value" displays correctly. However, when I include the required "name" attribute to work with [(ngModel)], the "value" attribute stops functioning. Without using the "name" attribute, an error ...

Storing Json data in a variable within Angular 2: a step-by-step guide

Within the params.value object, there are 3 arrays containing names that I need to extract and store in a variable. I attempted to use a ForEach loop for this purpose, but encountered an issue. Can you spot what's wrong? var roles = params.forEach(x ...

Next.JS is efficiently compressing images into base64 format, resulting in an empty image

I recently uploaded a pizza.jpg image to Cloudflare Pages and embedded it into a (.jsp file) page. <div className="product_img"> <Image src={'pizza.jpg'} loader={localLoader} alt={'Pizza'} width='300' he ...

Despite the onsubmit returning false, the submit operation still goes through

I seem to have hit a roadblock yet again. My registration form incorporates three JavaScript functions which display the desired output when triggered by an onchange event within my HTML form. These functions generate a Bootstrap alert while the user is co ...

Using JavaScript to pre-select a radio button without any user interaction

Is there a way to programmatically set a radio button in a group without physically clicking on the button? I am attempting to open a jQuery page and depending on a stored value, the corresponding radio button should be selected. I have researched similar ...

Struggling to retrieve the JSON information, but encountering no success

Here is the javascript code snippet: $.getJSON("validate_login.php", {username:$("#username").val(), password:$("#password").val()}, function(data){ alert("result: " + data.result); }); And here is the corresponding php code: <?ph ...

Error encountered by React context: TypeError - Attempting to iterate over an object that is not iterable (unable to access property

I'm encountering this error: TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator)) whenever I attempt to handle state using useContext. The purpose here is to initialize "tokens" as an empty array [] on page load, and then ...

Monitor modifications to an <input type="text"> element as its value is updated dynamically through JQuery from the server side

I am struggling with detecting when the value of an input field changes after it has been set by clicking a button. I have tried various events but can't seem to find the right one. <!DOCTYPE html> <html> <head> <script src=" ...

Assertion using Node.js with Selenium WebDriver

I am currently working on implementing assertions for testing using selenium webdriver with node js. However, I am encountering an issue where it returns undefined when trying to assert the page title (which is the URL of the page). It seems like I may n ...

Refreshing the identification of a button

I have been working on updating an ID with a value from another button. Here is my current progress: $('.viewemployment').on('click', function(e){ var url = '<?php echo Config::get('URL'); ?>dashboard/employmen ...

Enhancing Efficiency and Optimization with jQuery

Recently delving into the world of jQuery, I have been on the lookout for ways to enhance the speed and performance of my code. If anyone has any tips or valuable resources that could aid me in this endeavor, I would greatly appreciate it. Thank you, Bev ...

Updating of an Angular Directive within a nested Directive ceases once the inner Directive has been modified

Encountered a challenge with directives nested within each other in AngularJS. The issue is that both directives share the same property through a service and have an input to modify this property. The outer directive uses "transclude" to include the inner ...

What is the best way to apply a hover rule to a CSS class in order to change the color of a specific row when hovering in

I have managed to successfully apply a classname and add color to a specific row in my react-table. However, I am facing difficulty in adding a hover rule to this className to change the color when I hover over the row. Can someone guide me on how to apply ...

Having trouble retrieving an object from an event handler in ReactJS

const question = { quest : "What is my age?", answers : [16,15,21,30], correct : 21, } validateAnswer(){ let usersResponse = document.getElementById('ans-1').textContent; let response = this.question.correct; if(usersResp ...

Replace all existing content on the webpage with an exciting Unity game upon clicking

In an interesting experiment, I am trying to hide a secret href that, once clicked, has the power to wipe out everything on the page, leaving it temporarily blank before replacing it with a captivating Unity game that takes over the entire page. Let me sh ...

Building personalized error messages using graphql-js and express

It has come to my attention that you have the ability to create customized errors within graphql and graphql-express. https://codeburst.io/custom-errors-and-error-reporting-in-graphql-bbd398272aeb I recently implemented a custom Error feature, but it see ...

Function exhibiting varying behavior based on the form from which it is called

Currently, I'm utilizing AJAX to execute a server call, and I've noticed that the behavior of my function varies depending on its origin. Below is an excerpt of the code that's causing confusion: <html> <body> <script> ...