Get started with Javascript

Get started with vanilla Javascript

Render a page or component from Plasmic from plain Javascript using the REST API. This returns plain HTML that you can render anywhere, optionally including Javascript-hydrated interactivity.

const response = await fetch('https://codegen.plasmic.app/api/v1/loader/html/preview/PROJECTID/COMPONENTNAME?hydrate=1&embedHydrate=1', {
headers: {
// Your project ID and public API token
'x-plasmic-api-project-tokens': 'PROJECTID:APITOKEN'
// You can find your PROJECT token by visiting
// https://studio.plasmic.app/projects/[PROJECTID]/docs/loader#showToken=true
}
});
const result = await response.json();
document.body.innerHTML = result.html;

The above use the /preview/ route, which fetches the latest revisions, whether or not they were published! Replace with /published/ to ensure you render only published changes, or /versioned/ to render specific versions.

If you want to publish only static content and don’t want to hydrate any Javascript (don’t need any interactivity), remove the query parameters hydrate and embedHydrate.

Customization

The REST API let’s you customize both component props and global variants that should be passed down for the requested component.

const query = new URLSearchParams([
['hydrate', '1'],
['embedHydrate', '1'],
[
'componentProps',
JSON.stringify({
// Your component props
})
],
[
'globalVariants',
JSON.stringify([
// Your global variants
{
name: 'Theme',
value: 'Dark'
}
])
]
]);
const response = await fetch(`https://codegen.plasmic.app/api/v1/loader/html/preview/PROJECTID/COMPONENTNAME?${query}`, {
headers: {
// Your project ID and public API token
'x-plasmic-api-project-tokens': 'PROJECTID:APITOKEN'
// You can find your PROJECT token by visiting
// https://studio.plasmic.app/projects/[PROJECTID]/docs/loader#showToken=true
}
});
const result = await response.json();
document.body.innerHTML = result.html;

The componentProps field expects an object, you can override the props of the component and specify which component variants should be active. The globalVariants field expects an array with objects, each object describing a global variant, with name and value.

There’s much more to explore!

  • Perform server-side rendering.
  • Render different variants.
  • Override the content or props.
  • Add dynamic behavior.
Continue learning in the docs.