api not returning content but browser is
Unanswered
Philippine Crocodile posted this in #help-forum
Philippine CrocodileOP
hi all - i have a nextjs project and i'm trying to use puppeteer to take a screenshot of a specific page (which is also hosted by my project). i can navigate to the url directly on the browser and everything works fine but when i try accessing it via an api as shown below, the page never loads. not sure how to go about solving this. i do get a 200 status on postman however
code for the actual page that i'm tryna take a screenshot of (it keeps saying loading graphic even though it works fine when i go the website directly)
export async function GET(req: Request) {
const url = new URL(req.url);
const targetUrl = `http://localhost:3000/generate${url.search}`;
try {
const browser = await puppeteer.launch({
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});
const page = await browser.newPage();
await page.setViewport({ width: 1920, height: 1080, deviceScaleFactor: 2 });
await page.goto(targetUrl, { waitUntil: 'networkidle2', timeout: 15000 });
const screenshotBuffer = await page.screenshot({ type: 'png' });
await browser.close();
return new NextResponse(screenshotBuffer, {
status: 200,
headers: {
'Content-Type': 'image/png',
},
});
} catch (error) {
console.error('Error generating image with Puppeteer:', error);
return NextResponse.json(
{ error: 'Error generating image' },
{ status: 500 }
);
}
}
code for the actual page that i'm tryna take a screenshot of (it keeps saying loading graphic even though it works fine when i go the website directly)
useEffect(() => {
setFinalSVG(updatedSVG);
}, [searchParams]);
return (
<div style={{ padding: "20px" }}>
{finalSVG ? (
<div
style={{
padding: "10px",
background: "#fff",
maxWidth: "800px",
margin: "0 auto",
}}
dangerouslySetInnerHTML={{ __html: finalSVG }}
/>
) : (
<p>Loading graphic...</p>
)}
</div>
);
1 Reply
Philippine CrocodileOP
issue solved!! i used playwright instead and it worked