cloudflare / templates

A collection of starter templates and examples for Cloudflare Workers and Pages
https://cloudflareworkers.com
MIT License
999 stars 632 forks source link

Edge cache bypass if query string #30

Closed reinder42 closed 1 year ago

reinder42 commented 5 years ago

I've used the following code to bypass the edge cache if the request URL contains a query string, so that dynamic content based on the query string can still be generated at the origin.

addEventListener("fetch", event => {

...

let hasQueryString = false;
if(request.url && (request.url.indexOf('?') !== -1)) {
    hasQueryString = true;
}

if (configured && !isImage && !hasQueryString && upstreamCache === null) {

...

Does the above code make sense to bypass the cache, if there's a query string? Or should it use some other property of request? I just wanted to check – assuming it's a fairly typical use case :-)

pmeenan commented 5 years ago

Yes, that should work fine. Depending on how your site is configured that may bypass the cache a lot more often than you'd like (it's not unusual for WordPress to have the article ID as a query string for example).

You probably don't need to check request.url since it's impossible to come into the worker without one but I'm a fan of always being safe just in case so it doesn't hurt.

reinder42 commented 5 years ago

Great, thanks!

Depending on how your site is configured that may bypass the cache a lot more often than you'd like (it's not unusual for WordPress to have the article ID as a query string for example).

Good point. My website uses friendly URLs though, so query strings are only used for stuff like coupons on sales pages.

You probably don't need to check request.url since it's impossible to come into the worker without one but I'm a fan of always being safe just in case so it doesn't hurt.

Hehe, this script will work fine even if the internet doesn't use URLs ;-)

lauragift21 commented 1 year ago

Closing this issue because the initial question was addressed. Also the templates have moved over to the worker-sdk monorepo: https://github.com/cloudflare/workers-sdk/tree/main/templates.

if you're still experiencing issues feel free to open an issue there.