Serving static assets #
Static assets refer to JavaScript, stylesheets, images, fonts, etc. that are used in your views.
Setting up a directory to serve can be accomplished using the relevant version of router.path()
that accepts an instance of StaticHandlerOptions
:
void configure(Router router) {
router.path('/public/*', serve('public'))
}
This makes the contents of {PWD}/public
available at /public/*
.
You can also be more explicit by using regular expressions in the route path:
router.pathRegex('\\.(css|js|jpe?g|png)$', serve('public'))
The serve
method in diego.Application
will serve a directory using smart defaults depending on the application environment (the value for app.env
). These defaults are as follows:
Setting | Development | Production/Staging |
---|---|---|
Caching enabled? | ⬜ | ✅ |
Max-Age header | 0 | 1 hour |
Directory listing enabled? | ⬜ | ⬜ |
Max cache size | 0 | 20 |
Diego uses Vert.x Web’s StaticHandler
under the hood. Check out their
official docs for more information on how it operates.
If you store your assets in apublic
directory in your project root during development, you’ll be able to see changes to assets immediately without rebuilding your app. This is handy when working with front end build tools like Vite, WebPack and Gulp. At deploy time, copy thepublic
directory tosrc/main/resources
to include it as part of your JAR.
Customizing Caching Behaviour #
If you wish to customize the automatic caching behaviour, you can do so by providing your own instance of StaticHandlerOptions to the Application.serve method.
router.path('/public/*', serve(dir: 'public', cacheEnabled: true, maxAge: '365d', maxCacheSize: 100))
Further customization #
If you require even more control of the underlying StaticHandler, consider using a variation of router.use
or router.path
that supports a io.vertx.core.Handler<RouteContext>
. This way you can mount a custom
StaticHandler.
WebJars #
WebJars are served at /webjars/*
and are cached in all environments for
the maximum time allowed by the browser. There is no additional configuration required.
Next: Forms