dev-htmx v0.8.2
dev-htmx
Enables HTMX hypermedia applications from a frontend "bundler", e.g. Vite, Snowpack, WebPack, Rollup, or Parcel.
Install
npm install dev-htmximport
Then, in your main.js:
import devHtmx from 'dev-htmx';
devHtmx.init();Optional options object parameter to init:
appId: The value of theidattribute of the element in yourindex.htmlthat will contain your app's HTML content. Default:app.api: An object addressing the "API server" that renders the application's HTML. Default:{ protocol: 'http', address: 'localhost', port: '3000' }.dev: An object addressing the "development server" that your bundler can run to serve your unbundled assets. Default:{ protocol: 'http', address: 'localhost', port: '3001' }.- For
apianddev, you can pass any number of its properties to ovveride the default, e.g.{ port: 5000 }.
Features
Goal is to be able to be able to serve the frontend from the bundler's dev
server, while having the HTML content generated from the api server, and still
enjoying all development server features, like Hot Module Replacement.
- When partial HTML content is requested through Ajax, the request is directed
to the
apiserver, even if the app is currently running on thedevserver. - When loaded from the development server, the app's content is fetched
automatically from the
apiserver, and injected into theappIdelement of the localindex.html. To indicate that the complete app's HTML is needed, even though it's requested through Ajax, theHX-Initheader is sent along.
Example
An example setup, using Vite as the bundler, and Fastify as the (Nodejs) api server, can be found here: https://github.com/wscherphof/fastify-htmxample.
CORS
Note that when an Ajax request is made to the api server from the page served
by the dev server, the request is bound to the browser's Cross-Origin
Resource Sharing
policies.
This means the api server needs to explicitly allow requests from the dev
server origin, by providing the proper response header values.
The HTMX request headers should be listed in the CORS "allowed headers"; the HTMX response headers in the CORS "exposed headers".
An example of these settings can be found in the fastify-htmx plugin code.