Caching responses | laravel-responsecache-go | Spatie       

 SPATIE  

laravel-responsecache-go
========================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-responsecache-go](https://spatie.be/docs/laravel-responsecache-go/v1)  Basic-usage  Caching responses

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-responsecache-go/v1) 

  Caching responses    
- [ Introduction ](https://spatie.be/docs/laravel-responsecache-go/v1/introduction)
- [ Requirements ](https://spatie.be/docs/laravel-responsecache-go/v1/requirements)
- [ Installation &amp; setup ](https://spatie.be/docs/laravel-responsecache-go/v1/installation-setup)
- [ Questions and issues ](https://spatie.be/docs/laravel-responsecache-go/v1/questions-issues)
- [ Testing ](https://spatie.be/docs/laravel-responsecache-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/laravel-responsecache-go/v1/releasing)
- [ Changelog ](https://spatie.be/docs/laravel-responsecache-go/v1/changelog)
- [ Support us ](https://spatie.be/docs/laravel-responsecache-go/v1/support-us)
- [ About us ](https://spatie.be/docs/laravel-responsecache-go/v1/about-us)

Basic usage
-----------

- [ Caching responses ](https://spatie.be/docs/laravel-responsecache-go/v1/basic-usage/caching-responses)
- [ Flexible caching (SWR) ](https://spatie.be/docs/laravel-responsecache-go/v1/basic-usage/flexible-caching)
- [ Preventing caching ](https://spatie.be/docs/laravel-responsecache-go/v1/basic-usage/preventing-caching)
- [ Clearing the cache ](https://spatie.be/docs/laravel-responsecache-go/v1/basic-usage/clearing-the-cache)
- [ Using tags ](https://spatie.be/docs/laravel-responsecache-go/v1/basic-usage/using-tags)
- [ Events ](https://spatie.be/docs/laravel-responsecache-go/v1/basic-usage/events)

Advanced usage
--------------

- [ Custom cache profiles ](https://spatie.be/docs/laravel-responsecache-go/v1/advanced-usage/custom-cache-profiles)
- [ Creating a replacer ](https://spatie.be/docs/laravel-responsecache-go/v1/advanced-usage/creating-a-replacer)
- [ Customizing the serializer ](https://spatie.be/docs/laravel-responsecache-go/v1/advanced-usage/customizing-the-serializer)
- [ Customizing the hasher ](https://spatie.be/docs/laravel-responsecache-go/v1/advanced-usage/customizing-the-hasher)
- [ Configuration ](https://spatie.be/docs/laravel-responsecache-go/v1/advanced-usage/configuration)

 Caching responses
=================

###  On this page 

1. [ Using middleware ](#content-using-middleware)
2. [ Using attributes ](#content-using-attributes)
3. [ Cookies ](#content-cookies)
4. [ ETags and replacers ](#content-etags-and-replacers)
5. [ Minimum requests ](#content-minimum-requests)
6. [ Response lifecycle ](#content-response-lifecycle)

After installing the package, the `CacheResponse` middleware caches successful non-AJAX GET requests returning text based content for a week. Logged in users each have their own separate cache.

Using middleware
--------------------------------------------------------------------------------------------------------

You can configure caching per route using `For`.

```
pages := route.Middleware(responsecache.For(10 * time.Minute))
pages.Get("/about", pagesHandler.About)
pages.Get("/contact", pagesHandler.Contact)

route.Get("/posts", posts.Index).
    Middleware(responsecache.For(5 * time.Minute))

route.Get("/posts/{post}", posts.Show).
    Middleware(responsecache.For(time.Hour, "posts"))
```

Lifetimes are `time.Duration` values. `CacheResponse{}` uses the profile's lifetime. `For(0)` disables both reads and writes. A route's explicit lifetime takes precedence over the profile.

Using attributes
--------------------------------------------------------------------------------------------------------

Go has no controller attributes. Use typed route middleware instead of PHP's `#[Cache]`, `#[FlexibleCache]` and `#[NoCache]`. A route group replaces a class-level attribute. Keep exceptional routes outside that group or put `DoNotCache` before the cache.

Cookies
-----------------------------------------------------------------------------

Cookies belong to a visitor, not to a cached page. Both middleware leave cookies out of the stored copy. The visitor whose request first caches the page still receives cookies set by the handler.

On later requests, the handler does not run. If you need to set a cookie on every request, set it in middleware before the response cache middleware.

```
lastVisit := web.MiddlewareFunc(func(r *web.Request, next web.Next) *web.Response {
    return next(r).WithCookie(&http.Cookie{
        Name:  "last_visit",
        Value: date.Now(r).Format(time.RFC3339),
    })
})

route.Get("/posts", posts.Index).
    Middleware(lastVisit, responsecache.For(10 * time.Minute))
```

Session and CSRF cookies continue to work in Laravel's usual web middleware group. The built-in replacer removes the original CSRF token before storage and inserts the current session's token on hits. A cached placeholder without an active session is treated as a miss, never served to a visitor.

ETags and replacers
-----------------------------------------------------------------------------------------------------------------

An ETag identifies a version of a page. Replacers may change the cached body before it reaches the visitor, so the package removes `ETag` and `Content-Length` whenever a replacer changes the body. Unchanged bodies keep their validators. Laravel computes the outgoing content length.

Put middleware that computes final ETags outside response caching. Do not mark pages containing CSRF tokens or other visitor-specific content as public browser or proxy cache entries.

Minimum requests
--------------------------------------------------------------------------------------------------------

Set `Config.MinimumRequests` to avoid storing pages requested only once. Only eligible responses count. Counts expire after `MinimumRequestsLifetime`, defaulting to one day. A count of three stores the third eligible response. Overlapping cache middleware do not count a single request twice.

Response lifecycle
--------------------------------------------------------------------------------------------------------------

Storage happens after the response is sent, using the final buffered response. Body changes and same-media-type replacements from outer middleware are included. If outer middleware changes the approved status or media type, that response is not cached. The request key is captured before rendering.

Files, downloads, streams and other responses whose body is not buffered are not cached. An empty buffered body is supported. Native redirects with a Location header are supported even though Laravel Go does not give them a text content type.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
