Assets
elements man assetsAn asset is any file your app serves that is not code: an image, a font, a PDF, a download.
There are two kinds of asset, and each is served a different way:
- Static assets are files in your source tree. You know their names when you
write the code. They are content-hashed at build time and served from
/assets/. - Dynamic assets come from the database: a product photo, an avatar, an upload. You do not know the filename until the row is read, so a build-time URL cannot exist. These are served by a route.
Static assets
Put static assets anywhere under app/. The scaffold uses app/shared/assets/.
Directory layoutapp/shared/assets/ favicons/favicon.svg products/quad-lineup.jpg
In markup, write a path
app/pages/home/template.ehtml<img src="./hero.jpg" alt=""> <link rel="icon" href="../../shared/assets/favicons/favicon.svg">
Relative paths only. The build rewrites the attribute to the file's content-hashed URL:
Output<img src="/assets/app/pages/home/hero.a17f3c0b9d2e4a51.jpg" alt="">
The build rewrites src, href, poster and data, and the content of
the meta tags that hold URLs, such as og:image and twitter:image.
content is a generic attribute name, so the build rewrites it only on a
fixed list of meta properties that hold URLs.
It also works in CSS:
Example.hero { background-image: url("../assets/products/quad-lineup.jpg"); }
In code, import it
An import of a non-code file gives you its URL as a string:
Exampleimport favicon from "#app/shared/assets/favicons/favicon.svg"; favicon; // "/assets/app/shared/assets/favicons/favicon.f9e9effe4ae761bd.svg"
An import is the only way to store an asset URL in a variable. Import the asset when its URL is part of your data, such as a field in an array of objects, and not a single attribute written in a template:
Exampleimport quad from "#app/shared/assets/products/quad.jpg"; import sidecar from "#app/shared/assets/products/sidecar.jpg"; const CASES = [ { name: "Quad", photo: quad }, { name: "Sidecar", photo: sidecar }, ];
Template<li e:for={c of CASES}> <img src={c.photo} alt={c.name}> <span>{c.name}</span> </li>
The URL is inlined at build time, so there is no runtime lookup and no helper
to call. The build percent-encodes the file name in the URL and the server
decodes it, so a name with a space, %, #, ? or non-ASCII characters
works as it is. An imported asset and a path written in markup
produce the identical URL.
The server serves every asset that a file imports. An import in server-only
code counts, so a route that builds a webmanifest or an rss feed can import an
icon and get its /assets/ URL. An import in a file that no route uses counts
too: the import statement alone makes the server serve the asset.
Path or import: write a path when the file is in the same directory as
the template that uses it. Import the asset when several templates use it, or
when its URL has to be stored in a variable. The scaffold imports its favicon
because the file is in app/shared/assets/, a different directory from the
template in app/pages/home/.
# is for imports, not for URLs
#app/... is import-map syntax. It belongs in an import statement:
Importimport favicon from "#app/shared/assets/favicons/favicon.svg";
In an attribute or a CSS url(), # keeps its HTML and CSS meaning: a page
anchor or an SVG fragment reference. The build does not rewrite a value that
starts with #:
Not asset paths<a href="#pricing">Pricing</a> <!-- an anchor, untouched --> <img src="#app/shared/assets/logo.svg"> <!-- NOT an asset path -->
Example.icon { fill: url(#gradient); } /* an SVG paint server */
Bare imports
An import of an asset with no name and no from declares no variable, so
the build removes the statement:
Bare importimport "#app/shared/assets/logo.svg"; // no effect
A bare import of a .css file does have an effect. It links the stylesheet:
Stylesheet importimport "./style.css";
Web fonts
Preload the faces the first screen sets type in with a <link rel="preload">
in the page. Elements hashes font URLs like any other asset and does not add font
preloads itself, because a stylesheet does not say which faces a page uses: a
@font-face is a declaration, not a fetch, and unicode-range makes it
conditional. Elements does preload stylesheets, since the browser does not
discover an @imported stylesheet until its parent has downloaded.
Import the font so the hint points at the same hashed URL the stylesheet asks
for, and keep crossorigin on it. Fonts are fetched in CORS mode even
same-origin, and a preload without it downloads the file a second time:
Font importimport interRoman from "#app/shared/styles/fonts/Inter.subset.woff2";
Preload<link rel="preload" href={interRoman} as="font" type="font/woff2" crossorigin="anonymous" />
Faces you do not preload still work. The browser fetches each one when a
rule needs it: an italic when text below the fold uses it, or a full face
when the text has a character in its unicode-range.
Dynamic assets
When the filename is stored in a database row, serve the file from a route.
The bytes are stored in a Postgres bytea column, as below, or in S3 or any
object store with the object's key stored in the row. The route serves the
file the same way in both cases.
Store the file, with its content type and a hash you can cache on:
Schemacreate table photos ( id uuid primary key default uuidGenerateV7(), bytes bytea not null, mimeType text not null, hash text not null );
Serve them from a route. A route that returns bytes is not a page, so its file
goes in app/routes/:
app/routes/photos.tsimport { Request, Response, sql } from "@elements/app"; interface Photo { bytes: Buffer; mimeType: string; } export default function servePhoto(req: Request, res: Response) { let id = req.params.id; let photo = sql<Photo>(` select bytes, mimeType from photos where id = ${id}::uuid `).first(); if (!photo) { res.status(404); return ""; } res.setHeader("Content-Type", photo.mimeType); res.setHeader("Cache-Control", "public, max-age=31536000, immutable"); return photo.bytes; }
index.tsapp.route("/photos/:id", servePhoto);
Build the URL in the template from the row's id and hash:
Template<img src={`/photos/${row.photoId}?v=${row.hash}`} alt={row.name}>
The ?v=<hash> is what makes immutable safe: the URL changes when the bytes
change, so a browser can hold the old one forever without ever showing stale
content. Static assets get the same result from a hashed
filename.
For uploads, accepting the file in the first place, see
elements man recipes/file-upload.