This version of the documentation is outdated, and features documented here may work differently now. You can see the latest stable version of the docs here.
Modifying HTTP Headers
Most of the time, you shouldn't need to touch the HTTP headers of your Perseus templates, but sometimes you will need to. A particular example of this is if you want your users' browsers to only cache a page for a certain amount of time (the default for Perseus if five minutes), then you'd need to set the Cache-Control
header.
Perseus supports inserting arbitrary HTTP headers for any response from the server that successfully returns a page generated from the template those headers are defined for. You can do this like so (taken from here):
use perseus::{
http::header::{HeaderMap, HeaderName},
Html, RenderFnResultWithCause, Template,
};
use sycamore::prelude::{view, SsrNode, View};
#[perseus::make_rx(PageStateRx)]
struct PageState {
greeting: String,
}
#[perseus::template_rx]
pub fn index_page(state: PageStateRx) -> View<G> {
view! {
p { (state.greeting.get()) }
}
}
#[perseus::head]
pub fn head() -> View<SsrNode> {
view! {
title { "Index Page" }
}
}
pub fn get_template<G: Html>() -> Template<G> {
Template::new("index")
.template(index_page)
.head(head)
.build_state_fn(get_build_state)
.set_headers_fn(set_headers)
}
#[perseus::autoserde(build_state)]
pub async fn get_build_state(_path: String, _locale: String) -> RenderFnResultWithCause<PageState> {
Ok(PageState {
greeting: "Hello World!".to_string(),
})
}
// For legacy reasons, this takes an `Option<T>`, but, if you're generating state, it will always be here
// In v0.4.0, this will be updated to take just your page's state (if it has any)
#[perseus::autoserde(set_headers)]
pub fn set_headers(state: Option<PageState>) -> HeaderMap {
let mut map = HeaderMap::new();
map.insert(
HeaderName::from_lowercase(b"x-greeting").unwrap(),
state.unwrap().greeting.parse().unwrap(),
);
map
}
Of note here is the set_headers_fn
function, which returns a HeaderMap
. This is then used on the template with .set_headers_fn()
. Note that the function you provide will be given the state as an argument (ignored here, but it will be deserialized for you with #[perseus::autoserde(set_headers)]
), and you must return some headers (you can't return an error).