# Capture screenshots with a Cloudflare worker

Last updated february 08, 2023

If you don't want to use your backend to make API calls, or if you plan to use screenshots URLs directly in `img` tags, using a Cloudflare worker to proxy ApiFlash might be a good solution. In particular, this is useful for hiding your access key and leveraging Cloudflare's fast network delivery and caching capabilities.

To create a Cloudflare account, go to [cloudflare.com](https://www.cloudflare.com/) and sign up. From your dashboard, go to the **workers** section and create a new service. Give it a name, and choose any starter (it doesn't matter which one you choose). Then edit the worker with the following code. (don't forget to put your access key in the following code).

```javascript
export default {
    async fetch(request) {
        let queryString = new URL(request.url).search; // Get the query string from the request URL.
        queryString += "&access_key=YOUR_ACCESS_KEY_HERE" // Add your access key to the query string.
        return fetch("https://api.apiflash.com/v1/urltoimage" + queryString, {
            cf: { // Cloudflare-specific properties.
                cacheTtl: 86400, // Cache screenshots for 24 hours.
                cacheEverything: true // Caches all file types beyond the Cloudflare default cached content.
            }
        })
    },
};
```

Your Cloudflare worker is now proxying our screenshot API. All query string parameters are passed directly to ApiFlash, except for the `access_key` parameter, which is added by the worker.

You can now make API calls to ApiFlash through your worker (replace your worker name and subdomain).

```html
https://your-cf-worker-name.your-cf-subdomain.workers.dev/?url=https://example.com&wait_until=page_loaded
```

If you want to restrict the type of screenshots that can be made through your worker, you can add the needed checks. For example here is how you can restrict the target `url`.

```javascript
export default {
    async fetch(request) {
        let queryString = new URL(request.url).search; // Get the query string from the request URL.
        if (!new URLSearchParams(queryString).get("url").startsWith('https://target-domain.com')) {
            // Return a 403 response if the target URL does not start with https://target-domain.com
            return new Response('Forbidden URL', {status: 403});
        }
        queryString += "&access_key=YOUR_ACCESS_KEY_HERE" // Add your access key to the query string.
        return fetch("https://api.apiflash.com/v1/urltoimage" + queryString, {
            cf: { // Cloudflare-specific properties.
                cacheTtl: 86400, // Cache screenshots for 24 hours.
                cacheEverything: true // Caches all file types beyond the Cloudflare default cached content.
            }
        })
    },
};
```
