Next.js Discord

Discord Forum

Need help to programmatically trigger `next export` script to get static pages.

Unanswered
Atlantic salmon posted this in #help-forum
Open in Discord
Atlantic salmonOP
This below is my current implementation along with the error explained

5 Replies

Atlantic salmonOP
/api/export.ts
import { spawn } from 'child_process';
import { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
 console.log("Api Was Hit::")
 try {
   console.log('Export process started');
   // Spawn a child process to run the `next export` command
   const exportProcess = spawn(/^win/.test(process.platform) ? 'pnpm.cmd' : 'pnpm', ['run', 'export'], { timeout: 240000 });

   // Collect the output of the export process
   let exportProcessOutput = '';
   exportProcess.stdout.on('data', (data) => {
     exportProcessOutput += data.toString();
   });

   // Listen for any errors that occur during the export process
   exportProcess.on('error', (err) => {
     console.error(err);
     res.status(500).send('Error occurred during export process');
   });

   // Listen for when the export process completes
   exportProcess.on('close', (code) => {
     if (code !== 0) {
       console.error('Export process output:', exportProcessOutput);
       console.error(`Export process exited with code ${code}`);
       res.status(500).send('Export process failed');
     } else {
       console.log('Export process completed successfully');
       res.status(200).send('Export process completed successfully');
     }
   });
 } catch (error) {
   console.error(error);
   res.status(500).send('An error occurred');
 }
}
This below is the error that I am getting
Api Was Hit::
Export process started
API resolved without sending a response for /api/export, this may result in stalled requests.
Export process output: 
> @examples/trpc-next-prisma-starter@10.13.0 export E:\Github-clones\Codeless-Cms\Codeless-Cms
> next build && next export

info  - Linting and checking validity of types...
info  - Creating an optimized production build...
 ELIFECYCLE  Command failed with exit code 1.
I have already tested it by maually running the next export script and everything works perfectly fine
My requirement is to somehow trigger the next export and get the static pages on the push of a button