Search code examples
htmlrustrust-rocket

How do I serve a static HTML at API endpoint using Rocket?


I want to serve a simple HTML file as a response to a request to an API endpoint like / or api/. The only thing I have managed to find online is how to host the a static file as /index.html for example.


Solution

  • You can serve a single file from a route by returning NamedFile:

    use rocket::fs::NamedFile;
    use rocket::get;
    
    #[get("/api")]
    async fn serve_home_page() -> Result<NamedFile, std::io::Error> {
        NamedFile::open("index.html").await
    }
    

    This is the 0.5 API; if you're using 0.4 then change the import to rocket::response::NamedFile and remove the async/await syntax. You can also return a simple std::fs::File or tokio::fs::File, but the NamedFile will do the extra step of setting the correct Content-Type header based on the file extension.