Access the NextJs route and send information to the component

I've developed a NextJs application with an API route that calls an internal page to create a PDF file.

Here is the code snippet responsible for generating the PDF in my API route:

function serialize(obj) {
  var str = [];
  for (var p in obj)
    if (obj.hasOwnProperty(p)) {
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    }
  return str.join("&");
};

async function generatePdf(body) {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  // Allows you to intercept a request; must appear before
  // your first page.goto()
  await page.setRequestInterception(true);

  // Request intercept handler... will be triggered with
  // each page.goto() statement
  page.on("request", (interceptedRequest) => {
    // Here, is where you change the request method and
    // add your post data
    var data = {
      method: "POST",
      postData: serialize(body),
      headers: {
        ...interceptedRequest.headers(),
        "Content-Type": "application/x-www-form-urlencoded",
      },
    };

    // Request modified... finish sending!
    interceptedRequest.continue(data);

    // Immediately disable setRequestInterception, or all other requests will hang
    page.setRequestInterception(false);
  });

  const response = await page.goto(process.env.GEN_PDF_URL, {
    waitUntil: "networkidle2",
  });

  const pdf = await page.pdf({
    path: "test.pdf",
    printBackground: true,
    format: "a4",
  });
  const responseBody = await response.text();
  console.log(responseBody);
  await browser.close();

  return pdf;
}

The sendEmail method is called from the frontend and passes req.body as data to generate the PDF correctly.

async function sendEmail(req, res) {
  const pdf = await generatePdf(req.body);
  ...

I am contemplating whether it's feasible to dynamically generate the PDF based on the provider data sent through req.body in Next.js. This would enable me to create PDF files adaptively since the content of the PDF page varies depending on the data provided.

Answer №1

A situation similar to mine arose where I needed to generate a Next page from a third-party POST request.
For those who may still be questioning its feasibility, rest assured that it can indeed be done.

The solution lies in utilizing getServerSideProps in the following manner:

import { parseBody } from 'next/dist/server/api-utils/node';

export default function MyComponent({ body }) {
  // handle body data here
}

export const getServerSideProps = async ({ req }) => {
  return {
    props: { body: await parseBody(req) },
  };
};

While it's not achievable through Next.js 13+ app directory, it is feasible and encouraged to utilize both pages/ and app/ together in production.

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

Error loading GLTF file

I'm having trouble displaying a GLTF model using three.js. If someone could help me identify the issue in my code, I would greatly appreciate it. import {GLTFLoader} from "./GLTFLoader.js"; var scene = new THREE.Scene(); ...

Leveraging context.query in Next.js 13

It seems like the context.query I was relying on in Next.js 12 isn't functioning in version 13. What alternative can I use instead of context.query? Should I switch to Context API or useSearchParams? As a beginner developer, I'm feeling quite los ...

Encountering the AngularJS .Net Core routing $injector:modulerr error

I'm currently learning about .Net Core and AngularJS by following tutorials. However, I've encountered an error while attempting to implement client routing in the newest version of .Net Core with default configuration. The AngularJS error I rece ...

Every time I attempt to launch my Discord bot, I encounter an error message stating "ReferenceError: client is not defined." This issue is preventing my bot from starting up successfully

My setup includes the following code: const fs = require('fs'); client.commands = a new Discord Collection(); const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js')); for(const file of com ...

Combining Array Elements to Create a Unified Object with Vue

Is there a way to transform an array into a list of objects? Transform [ { "currenttime":43481.46983805556, "moped":"30 minutes", "car":"1 hour" } ] to { "currenttime":43481.46983805556, "moped":"30 minutes", ...

Implementing jQuery Table Sorting for File Sizes in a Rails Application

I am facing an issue where all columns in my table sort properly except for the Media column, which displays file size limits. I suspect that the Rails NumberHelper number_to_human_size method is causing a problem with tablesorter. Does anyone have any sug ...

Iterating through a series of AJAX requests in JavaScript until the variable equals "No" and then terminating the loop

After dedicating the past two days to my work, I am still struggling to find a solution. Any assistance would be greatly appreciated. My current setup involves nodejs and Vue. I need help figuring out how to break out of an AJAX call when receiving a "No" ...

tslint issues detected within a line of code in a function

I am a novice when it comes to tslint and typescript. Attempting to resolve the error: Unnecessary local variable - stackThird. Can someone guide me on how to rectify this issue? Despite research, I have not been successful in finding a solution. The err ...

Guide to utilizing the conditional operator to validate a field in vue.js

Here is an example of a text field: <input name="max-amount" v-validate="is_req=='required' : 'req' : ''" v-model="maxAmount"> I am looking to set up validation for this field with multiple ...

Having trouble importing Bootstrap into Next.js? It seems like the issue may be related to the

I am currently facing an issue with importing bootstrap 5.3.2 (not react-bootstrap) into my NextJS 14.1.0 project that utilizes the new App Router. My goal is to strategically utilize individual Bootstrap components (not through data-attrs). I managed to ...

Steps for presenting the information from the book

My current project involves creating an ebook using NodeJS, MongoDB, and Express. Right now, I am able to display all the chapters as a simple list, as shown in Fig. 1. However, I also want to include subchapters, where users can click on a chapter and vie ...

Concealing a Specific Element with Text using jQuery

Is there a way to conceal the section that includes the element labeled as "Product Tags" on a webpage? ...

Creating Chaos in PrimeFaces Page Navigation with JavaScript

I have implemented third-party connection monitoring code called Online JS by Denis Radin and it seems to be causing unexpected interactions with the navigation elements on my webpage. I am seeking insight into possible reasons for this behavior in order t ...

Dealing with the Back Button Problem in History API and History.js

Using Ajax to load the page presents a challenge when the user clicks the back button. Here is the scenario: Initial page (index.php) is loaded User clicks on a link The new page loads successfully via Ajax User clicks the back button The initial page is ...

Optimizing Midnight UTC+0 Setting in JavaScript Date Functions

I am using an MUI Datepicker that allows me to choose a day without specifying the time. For example, if I select 01.09.1970, in the console log it displays as Tue Sep 01 1970 00:00:00 GMT+0100 (Central European Standard Time). This indicates that even tho ...

Unable to retrieve scroll position utilizing 'window.scrollY' or 'window.pageYOffset'

Issue I am facing a problem where I need to determine the scroll position in order to adjust the tooltip position based on it. This is how my tooltip currently appears: However, when I scroll down, I want the tooltip to toggle downwards instead of its c ...

Guidelines for attaining seamless motion animation utilizing devicemotion rotationRate information

I am utilizing the rotationRate data obtained from the devicemotion eventListener to manipulate a three.js scene by tilting. The scene does respond to the data accurately in terms of angle adjustments, but it produces an unsmooth motion effect. Is there a ...

Is it possible to retain the volume level setting?

Whenever I am playing music and adjust the volume to 20%, the settings reset to 100% when the bot leaves the voice channel. It's frustrating having to manually set it back to 20% each time. Is there a way for my bot to remember the volume setting? con ...

Reverse a filter within an ng-repeat loop - AngularJS

I have a question that I haven't found the answer to yet. Here is the issue I'm facing: The JSON data I am working with has this structure: [{ "batch_queue_name": "Batch One", "start_date": "12/01/2016 10:18 P.M.", "end_date": "12/03/2016 ...

How can you efficiently transfer the expression utilized in v-for from the template to the component code?

How can I extract the expression within the template that is contained in :class? <div v-for="(user, index) in users" :key="index" :class="{'bg-yellow-lighter': infoWindowMarker && infoWindowMarker.position.lat === user.posit ...