Tutorial

Screenshot and PDF Generation in Astro with SnapAPI

April 2026 — 6 min read

Astro is the content-focused web framework that ships zero JavaScript to the browser by default, delivering exceptional performance for blogs, documentation sites, and marketing pages. Its API endpoints run server-side and can call external services without exposing secrets to the client. In this tutorial, you will add screenshot and PDF generation to an Astro site using SnapAPI, implementing the endpoint in an Astro API route, protecting it with a simple API key check, and returning binary responses efficiently.

Astro API Endpoints for Screenshot Generation

Astro API endpoints are defined as .ts or .js files with a GET or POST export in the src/pages/api/ directory. They run server-side when Astro is deployed in SSR mode using an adapter like the Node.js, Vercel, or Netlify adapter. Create a file at src/pages/api/screenshot.ts that exports a GET function. The function receives an APIContext object with access to the request URL, headers, and Astro's runtime environment. Extract the target URL from the query string, validate it, call SnapAPI, and return the binary response.

Enabling SSR in Astro

Astro is a static site generator by default. To use API endpoints that make server-side calls, you need to enable SSR by adding an adapter to your astro.config.mjs. For Node.js deployment, install the @astrojs/node adapter and set output: 'server' in your Astro config. For Vercel, use @astrojs/vercel. For Cloudflare Pages, use @astrojs/cloudflare. The adapter handles the server runtime so your API endpoint code is identical across deployment targets. Your SnapAPI key is stored in a .env file and accessed through Astro's import.meta.env object, which Astro guarantees is only available server-side when prefixed appropriately.

Environment Variables and Key Security

Astro distinguishes between public and private environment variables using naming conventions. Variables prefixed with PUBLIC_ are available both server-side and in client-side components. Variables without this prefix are only available in server-side code including API endpoints. Store your SnapAPI key as SNAPAPI_KEY in your .env file without the PUBLIC_ prefix. Access it in your API endpoint with import.meta.env.SNAPAPI_KEY. Astro's build process ensures this variable never appears in client JavaScript bundles, keeping your key secure even if your site's JavaScript is inspected.

Calling SnapAPI and Returning Binary Data

Inside your Astro API endpoint, use the native fetch API to call the SnapAPI screenshot endpoint. Pass the validated target URL as a query parameter and your SnapAPI key in the Authorization header. When the SnapAPI response arrives, check the status code and construct an Astro Response object from the response body buffer. Set the Content-Type header to match the SnapAPI response -- image/png for screenshots or application/pdf for PDFs. Astro's response handling correctly serializes the binary content without any additional encoding or base64 conversion.

Generating OG Images for Astro Blog Posts

One of the most compelling uses of SnapAPI in Astro sites is automated Open Graph image generation for blog posts. Create a dedicated Astro API endpoint at src/pages/api/og/[slug].ts that accepts a post slug, retrieves the post metadata from your content collection, renders an HTML template with the post title and metadata, passes the template URL to SnapAPI, and returns the PNG. Reference this endpoint URL in your blog post layout's Open Graph meta tags. When social platforms crawl your post URLs, they request the OG image endpoint, which generates a unique branded image for each post. Astro's content collections make it straightforward to retrieve post metadata from your Markdown frontmatter for use in the OG image template.

Caching Screenshot Responses

Screenshot generation adds one to five seconds of latency to each unique request. For public-facing endpoints, caching is essential. Set Cache-Control headers on your Astro screenshot API response to tell CDN edge nodes and browsers to cache the result. For Vercel deployment, Astro's Vercel adapter propagates Cache-Control headers to Vercel's Edge Network automatically. For Cloudflare Pages deployment, set Cache-Control headers with appropriate max-age values and Cloudflare's CDN caches the screenshot at the edge closest to each requester. Subsequent requests for the same screenshot URL are served from cache in milliseconds without hitting your Astro server or consuming SnapAPI credits.

Advanced Astro Screenshot Patterns

The basic Astro API endpoint approach handles the common screenshot generation use case cleanly. For Astro sites with specific performance, security, or integration requirements, several advanced patterns extend the core implementation in useful directions.

Hybrid Rendering for Screenshot Endpoints

Astro's hybrid rendering mode allows you to combine static pre-rendering with server-side rendering on a per-page basis. In a hybrid Astro site, most pages are statically generated at build time for maximum performance, while specific pages -- including your screenshot API endpoint -- run server-side on demand. Enable hybrid rendering by setting output: 'hybrid' in your Astro config and adding your adapter. Add export const prerender = false to your screenshot API endpoint file to ensure it runs server-side on every request rather than being pre-rendered at build time. This gives you the best of both worlds: static performance for content pages and server-side flexibility for your screenshot endpoint.

Middleware for Request Validation

Astro's middleware system runs before every request, making it the correct location for cross-cutting concerns like API key validation and rate limiting. Create a middleware file at src/middleware.ts that checks the Authorization header on requests to your /api/screenshot endpoint. If the header is missing or invalid, return a 401 response immediately before the API endpoint handler runs. Store valid API keys in your environment variables or in a database. This middleware approach allows you to issue different API keys to different consumers and revoke them individually without changing your endpoint code.

Integration with Astro Content Collections

Astro's content collections provide a type-safe API for accessing your site's Markdown and MDX content. Screenshot generation integrates naturally with content collections for generating OG images and content preview cards. In your screenshot API endpoint, use getCollection to retrieve post metadata from your content collection, then construct an OG image template URL populated with the post's title, author, publication date, and category tag. Pass this template URL to SnapAPI and return the resulting PNG. Because the template URL construction is based on your content collection schema, the OG image content is always synchronized with your actual post content without any manual maintenance.

Edge Deployment Considerations

When deploying Astro to Cloudflare Pages with the Cloudflare adapter, your API endpoint runs in the Cloudflare Workers environment, which uses the V8 isolate runtime rather than Node.js. The native fetch API is available in Workers, making the SnapAPI call syntax identical to Node.js deployments. However, Workers have a 128MB memory limit and a CPU time limit per request. For screenshot endpoints handling large full-page captures, these limits are rarely a concern since the SnapAPI response is streamed directly to the client without buffering. Response caching is particularly important in edge deployments because Cloudflare's global CDN can serve cached screenshots from the edge node closest to each requester, dramatically reducing both latency and Workers invocation costs for frequently requested screenshot URLs.

Testing Astro Screenshot Endpoints

Astro's testing story for API endpoints involves using Astro's createServer test utility to spin up a test server instance and making HTTP requests to your endpoint using the native fetch API. For screenshot endpoint tests, mock the outbound SnapAPI fetch call using your test framework's module mocking capabilities -- Vitest's vi.mock for Vitest users. Your mock returns a pre-stored PNG buffer, allowing your tests to verify correct header handling, error response structure, and caching behavior without making real SnapAPI calls during CI runs. Write tests for valid URL requests, invalid URL rejection, missing authorization, and SnapAPI timeout simulation. Add these tests to your Astro project's CI pipeline so screenshot endpoint regressions are caught before deployment. For production validation, maintain a small set of integration tests that run against your staging deployment and make real SnapAPI calls to verify end-to-end functionality after each release. Get started with the free tier at snapapi.pics.

Astro is one of the fastest growing frameworks for content sites and documentation, and SnapAPI integrates with it through the same server-route pattern that works across all Astro deployment targets. Whether you are building a blog, a marketing site, or a documentation portal with Astro, adding screenshot and PDF generation to your server API routes takes under an hour using the patterns in this guide. Sign up for your free SnapAPI key at snapapi.pics and ship your first screenshot endpoint today.