# assets Fetch-based server for compiling browser assets on demand. ## Features - **On-Demand Compilation** - Compile browser scripts and styles on demand - **File Serving** - Serve configured file assets like images and fonts with optional transforms - **Access Control** - Control exactly which files and packages can be served - **Preloads** - Generate preload URLs for scripts and styles based on imports - **Inspection** - List browser-reachable assets and explain URL-to-file mappings - **Caching** - Conservative caching by default with stable URLs, ETags, and revalidation - **Optional Fingerprinting** - Content-based fingerprinted URLs for long-lived browser caching - **Source Maps** - Serve inline or external sourcemaps - **Hot Module Reloading** - Handle live code updates in development - **Script Loaders** - Post-process compiled JavaScript with Node-compatible loaders ## Installation ```sh npm i remix ``` The optional image transform examples also use Sharp: ```sh npm i sharp ``` ## Usage Use `createAssetServer` to serve browser assets from a URL namespace in your app. ```ts import { createRouter } from 'remix/router' import { createAssetServer } from 'remix/assets' let assetServer = createAssetServer({ basePath: '/assets', allowFiles: ['app/routes.ts', 'app/**/public/**'], allowPackages: ['remix'], files: { extensions: ['.svg', '.png', '.jpg', '.jpeg', '.woff2'], }, }) let router = createRouter() router.get('/assets/*', ({ request }) => { return assetServer.fetch(request) }) ``` This example gives you an `/assets/*` endpoint that serves compiled browser source from `public/` directories throughout `app/` and from the `remix` package. ## Shared Configuration Keep JSON-compatible asset mapping, access, and file-type settings in `remix.json` so the running server and Remix CLI use the same configuration: ```jsonc { "$schema": "./node_modules/remix/schema/remix.json", "assets": { "basePath": "/assets", "mounts": { "app": "app", "npm": "node_modules", }, "allowFiles": ["app/routes.ts", "app/**/public/**"], "allowPackages": ["remix"], "denyFiles": ["app/**/*.test.*"], "files": { "extensions": [".svg", ".png", ".jpg", ".woff2"], }, }, } ``` Load it from application code and add runtime-only behavior there: ```ts import { createAssetServer, defineFileTransform } from 'remix/assets' import { loadConfig } from 'remix/cli' import sharp from 'sharp' let config = await loadConfig(import.meta.dirname) if (config.assets === undefined) throw new Error('Missing assets configuration') if (config.assets.files === undefined) throw new Error('Missing asset file configuration') let assetServer = createAssetServer({ ...config.assets, files: { ...config.assets.files, transforms: { webp: defineFileTransform({ extensions: ['.png', '.jpg'], async transform(bytes) { return { content: await sharp(bytes).webp({ quality: 80 }).toBuffer(), extension: '.webp', } }, }), }, }, }) ``` `loadConfig()` accepts either a config file or a directory. When given a directory, it searches upward for the nearest `remix.json`. Run `remix assets` to list reachable files, or `remix assets inspect ` to inspect one mapping and its access decision. ## Root Directory Use `rootDir` to specify the root directory of the asset server, which is used to resolve relative file paths. Defaults to `process.cwd()`. ```ts import * as path from 'node:path' import { createAssetServer } from 'remix/assets' let assetServer = createAssetServer({ rootDir: path.resolve(import.meta.dirname, '..'), basePath: '/assets', allowFiles: ['app/routes.ts', 'app/**/public/**'], allowPackages: ['remix'], }) ``` ## Access Control You must provide an `allowFiles` list to specify which files are allowed to be served. You can also allow whole packages by name with `allowPackages`. `denyFiles` is optional and takes precedence over both `allowFiles` and `allowPackages`. ```ts import { createAssetServer } from 'remix/assets' let assetServer = createAssetServer({ basePath: '/assets', allowFiles: ['app/routes.ts', 'app/**/public/**'], allowPackages: ['remix'], denyFiles: ['app/**/*.server.*'], }) ``` Values for `allowFiles` and `denyFiles` are file paths or globs. Relative values are resolved from `rootDir`. Absolute file paths match exactly, and absolute directory paths also match their descendants. Values for `allowPackages` are exact package names. Dependencies and installed optional dependencies of packages in `allowPackages` are also allowed automatically. Peer dependencies must be listed explicitly if they should be browser-reachable. Allowed package files must still be reachable through `mounts`. ## Mounts By default, the asset server mounts the `app` directory at `/app` and `node_modules` at `/npm`. Use `mounts` to replace these defaults. Keys are public paths relative to `basePath`, and values are directory paths relative to `rootDir`. ```ts import { createAssetServer } from 'remix/assets' let assetServer = createAssetServer({ basePath: '/assets', mounts: { source: 'app', vendor: 'node_modules', }, allowFiles: ['app/routes.ts', 'app/**/public/**'], allowPackages: ['remix'], }) ``` Package managers that install outside `rootDir`, such as pnpm's global virtual store, are handled without configuration: the asset server reads the store location from the nearest `node_modules/.modules.yaml` and mounts it internally so those package files still resolve to public URLs. A store that a configured mount already covers, such as pnpm's default `node_modules/.pnpm`, is left alone. ### File watching The file system is watched by default so source changes are picked up without requiring a server restart. ```ts import { createAssetServer } from 'remix/assets' let assetServer = createAssetServer({ basePath: '/assets', allowFiles: ['app/routes.ts', 'app/**/public/**'], allowPackages: ['remix'], }) ``` When finished with the asset server, call `await assetServer.close()` to clean up the file watcher. ```ts await assetServer.close() ``` You can disable file watching if the files on disk won't change, or if watching is managed at a higher level (e.g. Node's `--watch` flag). ```ts import { createAssetServer } from 'remix/assets' let assetServer = createAssetServer({ basePath: '/assets', allowFiles: ['app/routes.ts', 'app/**/public/**'], allowPackages: ['remix'], watch: false, }) ``` You can optionally provide an array of glob patterns to the `watch.ignore` option: ```ts import { createAssetServer } from 'remix/assets' let assetServer = createAssetServer({ basePath: '/assets', allowFiles: ['app/routes.ts', 'app/**/public/**'], allowPackages: ['remix'], watch: { ignore: ['**/node_modules/**'], }, }) ``` ## Script Entries Use `assetServer.getScriptEntry()` to get everything needed to load a script and its dependencies. ```ts let { href, importMap, preloads } = await assetServer.getScriptEntry('app/assets/entry.tsx') ``` Script entry metadata is cached between calls and refreshed when a watched file changes. Each call returns a separate copy, so changing the returned object does not affect later calls. This can be used when rendering a document shell: ```tsx import type { Handle, RemixNode } from 'remix/component' import { ImportMap } from 'remix/component/server' import { assetServer } from './assets.ts' let { href, importMap, preloads } = await assetServer.getScriptEntry('app/assets/entry.tsx') export function Document(handle: Handle<{ children: RemixNode }>) { return () => ( {/* ... */} {preloads.map((preload) => ( ))}