hotwired / turbo

The speed of a single-page web application without having to write any JavaScript
https://turbo.hotwired.dev
MIT License
6.64k stars 421 forks source link

Turbo Frame + Nginx Cache #1294

Open eduardolagares opened 1 month ago

eduardolagares commented 1 month ago

Hello,

I'm trying to use the nginx cache in my application and I came across the following problem.

I noticed that when loading a Frame, turbo adds the Turbo-Frame header: frame-name. This makes sense because I need to check in rails whether I am in a request called by a Frame or not. So far so good, the problem is that now I have 2 responses for the same url.

Ex:

passwords/new -> (directly called) is rendered by layouts/application
passwords/new -> (called by a turbo frame) is rendered by layouts/turbo_rails/frame

The problem here is that for nginx the path is always passwords/new and it is impossible to cache this route because at times nginx will deliver the same content to both.

In the same way that turbo adds the Turbo-Frame, I would like to add an extra parameter to this url. To do this I used the code below:

document.addEventListener("turbo:before-fetch-request", (event) => {
  event.detail.url.searchParams.append('turbo', 'frame')
})

This caused the Frame request to be sent with an extra parameter, temporarily solving the cache problem.

Now my main problem is that in links with data-action="advance" the url that is applied in the browser is passwords/new?turbo=frame, completely breaking the cache because this route is a partial render and not a complete render

Has anyone here used Turbo Frame with nginx cache and found a solution to this problem? I tried to intercept the url change in the browser in several ways but without success.

In summary, I need:

- Browser load sessions/new
- User click in a link frame to passwords/new 
- Frame is load with passwords/new?turbo=frame
- Browser url is changed to passwords/new (without turbo=frame)
4lllex commented 2 weeks ago

I think, you can just set proxy_cache_key to include Turbo-Frame header:

proxy_cache_key $scheme$proxy_host$request_uri$http_turbo_frame;

https://serverfault.com/questions/668178/change-proxy-cache-key-to-use-header-token-as-part-of-its-key