How to serve a static directory? #129
-
Because there's no opinion on the frontend part, in my use case, I'd like to serve frontend as static files. In axum, this can be achieve by Router::new()
.nest_service("/assets", get_service(ServeDir::new("dist/assets")))
.fallback_service(get_service(ServeFile::new("dist/index.html"))) Is this possible in loco? Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
Hey @flappyBug you can implement the after_routes hook. For example: pub struct App;
#[async_trait]
impl Hooks for App {
....
fn after_routes(router: AxumRouter, _ctx: &AppContext) -> Result<AxumRouter> {
let router = router.nest_service("/assets", get_service(ServeDir::new("dist/assets")))
.fallback_service(get_service(ServeFile::new("dist/index.html")));
Ok(router)
}
....
} |
Beta Was this translation helpful? Give feedback.
-
After a brief discussion with @jondot, we've come to the realization that supporting static asset serving can be seamlessly handled as a middleware in Loco, without the need to rely on the hook in this particular scenario. for example, middlewares:
static:
folder: frontent/dist
fallback: frontent/dist/index.html
... and loco will will implement the what do you think? |
Beta Was this translation helpful? Give feedback.
-
Thanks @flappyBug for bringing up this question. We believe it's essential to include this in the Loco library. I've added a static middleware to address this scenario. Check out the details in the #134. |
Beta Was this translation helpful? Give feedback.
-
@kaplanelad Thank you for adopting this feature. It's fantastic to see official support for static asset serving in loco. Regarding the configuration entry, introducing a prefix might be beneficial (alternatively, placing assets in a subfolder could serve as a workaround). One aspect I'm uncertain about with axum is the feasibility of having exclusive endpoints for the fallback service. Specifically, I'm interested in routing all fallbacks to index.html, with the exception of paths under |
Beta Was this translation helpful? Give feedback.
Hey @flappyBug
you can implement the after_routes hook.
The hook provides access to the Axum router, making both the
nest_service
andfallback_service
available for your use.For example: