Supercharge Your Next.js Apps with Dynamic Screenshots using Screenshotly
Discover how to seamlessly integrate Screenshotly into your Next.js projects for powerful server-side and client-side screenshot generation.
Next.js is a powerhouse for building modern web applications, and when combined with Screenshotly, you can unlock dynamic, on-the-fly screenshot capabilities. Whether you need to generate screenshots at build time, server-side, or via API routes for client-side requests, Screenshotly offers a flexible solution.
Server-Side Rendering (SSR) with "getServerSideProps"
Fetching screenshots directly within "getServerSideProps" allows you to serve pages with fresh, dynamic images. This is perfect for critical visuals that need to be up-to-date with every page load.
Example:
// pages/index.js
// Ensure you have the 'screenshotly' library installed and configured
// import screenshotly from 'screenshotly'; // Or your specific import
export async function getServerSideProps(context) {
try {
// Consider fetching the URL from a dynamic source or context
const targetUrl = 'https://example.com';
const options = {
format: 'jpeg', // Specify format (jpeg, png, webp)
quality: 80, // For JPEG/WebP, control quality
fullPage: true, // Capture the full scrollable page
// Add other Screenshotly options as needed: viewport, delay, etc.
};
const image = await screenshotly.capture(targetUrl, options);
// Pass the image URL or data to your page component
return {
props: { imageUrl: image.url }, // Assuming 'image.url' contains the accessible URL
};
} catch (error) {
console.error('Failed to capture screenshot:', error);
// Handle error gracefully, perhaps return a fallback image or error message
return {
props: { imageUrl: '/images/fallback-screenshot.png' }, // Example fallback
};
}
}
function HomePage({ imageUrl }) {
return (
<div>
<h1>Dynamic Screenshot</h1>
<img src={imageUrl} alt="Dynamic screenshot captured by Screenshotly" />
</div>
);
}
export default HomePage;
Pro Tip: While powerful, fetching screenshots in "getServerSideProps" for every request can impact performance if the screenshot generation is slow. For less critical images or pages with high traffic, consider generating screenshots via an API route and fetching them client-side, or use Incremental Static Regeneration (ISR) with "getStaticProps" and "revalidate".
Exposing an API Route for Client-Side Use
Need to generate screenshots on demand from the client? An API route is the perfect solution. This approach offers flexibility and can offload screenshot generation from the main page rendering path.
Example:
// pages/api/screenshot.js
// import screenshotly from 'screenshotly'; // Or your specific import
export default async function handler(req, res) {
if (req.method !== 'GET') {
return res.status(405).json({ message: 'Method Not Allowed' });
}
const { url, format = 'png', fullPage = 'false' } = req.query;
if (!url) {
return res.status(400).json({ message: 'URL parameter is required' });
}
// Basic URL validation (enhance as needed for security)
try {
new URL(url); // Will throw an error if the URL is invalid
} catch (error) {
return res.status(400).json({ message: 'Invalid URL provided' });
}
// Add more robust validation and sanitization for the URL to prevent abuse.
// For example, check against a whitelist of allowed domains.
try {
const options = {
format,
fullPage: fullPage === 'true',
// You can allow more options via query parameters, but validate them carefully!
// e.g., viewport: { width: parseInt(req.query.width) || 1280, height: parseInt(req.query.height) || 720 }
};
const image = await screenshotly.capture(url, options);
// Depending on how screenshotly returns the image (e.g., buffer, path, URL)
// you might need to set appropriate headers and send the image data directly
// or return a JSON response with the image URL.
// If 'image' contains the image buffer:
// res.setHeader('Content-Type', `image/${format}`);
// res.status(200).send(image.data); // Assuming image.data is the buffer
// If 'image' contains a URL to the stored image:
res.status(200).json({ imageUrl: image.url });
} catch (error) {
console.error('Screenshot API error:', error);
res.status(500).json({ message: 'Failed to capture screenshot' });
}
}
Security Note: When exposing an API route that takes a URL, always validate and sanitize the input "url" parameter to prevent potential security vulnerabilities like Server-Side Request Forgery (SSRF). Consider restricting allowed domains or protocols.
By leveraging Screenshotly with Next.js, you can create more dynamic, visually rich, and informative web applications. Start integrating today and bring your pages to life with automated screenshots!
Code examples feature syntax highlighting. Click anywhere in a code block to copy its contents.
Supported languages: JavaScript, TypeScript, Vue, HTML, CSS, JSON, Bash, and Markdown.