JavaScript Website SDK
One browser script for Gorilla Dash content and chat. Use it with plain JavaScript, WordPress, Vue, React, Laravel or another website stack.
The frontend and backend are separate packages. @gorilladash/website-sdk is JavaScript. gorilladash/laravel-website-sdk is the optional Laravel package for server-side content and caching.
For a guided setup, read Add Gorilla Dash content and a chatbot to your website.
Installation
Load the browser script once. Without chatbot settings, it makes no chatbot requests.
<script src="https://gorilladash.com/website-sdk.js?v=1" defer></script>
Browser support: the SDK script is supported on Chrome and Edge 103, Firefox 100 and Safari 16, or later. In older browsers it may fail to load or its content requests may fail, and the chatbot bundled in it may not start. If a site must offer chat to older browsers, keep the standalone chat-widget.js embed, which does not have this requirement.
The @gorilladash/website-sdk module package, which exposes the same content client and an optional Apollo adapter, is not yet available from npm. Use the browser script above unless Gorilla Dash support has supplied the module to you; the module examples below apply once you have it.
Website content
Run after the SDK has loaded, for example in your own deferred script. Requests go from the browser directly to the Gorilla Dash GraphQL endpoint. The client returns the GraphQL data object.
const client = GorillaDash.createClient({
accessToken: () => window.websiteAccessToken,
})
try {
const data = await client.query(`
query WebsiteInfo {
websiteInfo { name url base_products_path base_tribes_path }
}
`)
document.querySelector('#website-name').textContent = data.websiteInfo.name
} catch (error) {
document.querySelector('#website-name').textContent = 'Content unavailable'
}
For module imports, call createWebsiteClient with the same options. Query variables are the second argument and an optional operation name is the third. See the GraphQL query reference for pages, products, locations and other content.
Authentication
Your website uses two kinds of token, and only one of them ever reaches the browser.
| Token | Where it lives | What it can do |
|---|---|---|
| Website token | Your server only. Lasts 15 days. | Everything the GraphQL API offers, including enquiries, forms, reviews, sign-ins and orders. |
| Browser token | The page you send to the visitor. Lasts one hour. | Read published content only: pages, menus, articles, tribes, products and the rest, with any arguments, such as page numbers, search terms and filters. It cannot send anything, and cannot read a visitor's sign-in, cart or order. |
Your server gets the website token by exchanging the website's API ID and API Access Token, then exchanges the website token for a browser token and writes that into the page. The API Access Token, which is the OAuth client secret, never leaves your server. The Public Key authenticates cache-clear webhooks; it is not a GraphQL bearer token.
Issue both tokens from your server
This example uses the Fetch API available in Node 18 and later; the same steps work in PHP, Python or any other server language. It keeps each token in memory and asks for a new one shortly before the old one expires, so Gorilla Dash is asked about once an hour rather than on every page view. Keep that cache: the exchange accepts at most 60 requests a minute from each website. Asking again while a browser token has at least fifteen minutes left returns the same token, so several servers behind one website share it.
// Runs on your server. The API Access Token never reaches the browser.
const tokens = {}
const pending = {}
// Pages rendered at the same moment share one request for a new token.
async function cached(name, minimumMs, request) {
const token = tokens[name]
if (token && token.expiresAt - Date.now() > minimumMs) return token.value
pending[name] ??= (async () => {
const response = await request()
if (!response.ok) {
// A refused exchange means the website token was revoked, so forget it
// and fetch a new one next time.
if (name === 'browser' && [401, 404].includes(response.status)) delete tokens.website
throw new Error(`Gorilla Dash token request failed (${response.status})`)
}
const body = await response.json()
const { access_token, expires_in } = body.data ?? body
tokens[name] = { value: access_token, expiresAt: Date.now() + expires_in * 1000 }
return access_token
})().finally(() => delete pending[name])
return pending[name]
}
// After Gorilla Dash refuses a token (the API Access Token was regenerated),
// forget both cached tokens so the next request fetches new ones. At most once
// a minute, so visitors cannot use it to flood the exchange.
let lastForcedRefresh = 0
function forgetTokensIfAsked(forceRefresh) {
if (!forceRefresh || Date.now() - lastForcedRefresh < 60 * 1000) return
lastForcedRefresh = Date.now()
delete tokens.website
delete tokens.browser
}
// Full access. Use it for server rendering and to send enquiries and forms.
export function websiteAccessToken({ forceRefresh = false } = {}) {
forgetTokensIfAsked(forceRefresh)
return cached('website', 24 * 60 * 60 * 1000, () =>
fetch('https://graphql.gorilladash.com/oauth/token', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'User-Agent': 'example-website/1.0' },
body: JSON.stringify({
grant_type: 'client_credentials',
client_id: process.env.GORILLA_DASH_API_WEBSITE_ID,
client_secret: process.env.GORILLA_DASH_API_ACCESS_TOKEN,
}),
})
)
}
// Read-only. The only token you give to the browser.
export function browserAccessToken({ forceRefresh = false } = {}) {
forgetTokensIfAsked(forceRefresh)
return cached('browser', 10 * 60 * 1000, async () =>
fetch('https://graphql.gorilladash.com/oauth/website-browser-token', {
method: 'POST',
headers: {
Authorization: `Bearer ${await websiteAccessToken()}`,
'User-Agent': 'example-website/1.0',
},
})
)
}
Write the browser token into the page your server returns, before the SDK script, and give the browser a small address on your own site that returns a fresh one:
<script>window.websiteAccessToken = "…the value from browserAccessToken()…"</script>
// On your server, for example with Fastify. ?refresh=1 means Gorilla Dash
// refused the last token, so the cached one must not be handed out again.
app.get('/gorilla-dash-token', async (request, reply) =>
reply.header('Cache-Control', 'no-store').send({
access_token: await browserAccessToken({ forceRefresh: request.query.refresh === '1' }),
})
)
The accessToken option takes a token or a function. The examples on this page pass () => window.websiteAccessToken, which is enough for a page that is not left open for long. When a page can stay open longer than the token lasts, pass a function that fetches a new token when asked. After Gorilla Dash refuses an expired token, the SDK calls the function once with forceRefresh: true and repeats the request with the new token:
let browserToken = window.websiteAccessToken
let refreshing = null
const client = GorillaDash.createClient({
accessToken: ({ forceRefresh }) => {
if (!forceRefresh && browserToken) return browserToken
// Several refused queries at once still make one request for a new token.
refreshing ??= fetch(forceRefresh ? '/gorilla-dash-token?refresh=1' : '/gorilla-dash-token')
.then((response) => {
if (!response.ok) throw new Error(`Token refresh failed (${response.status})`)
return response.json()
})
.then((body) => (browserToken = body.access_token))
.finally(() => (refreshing = null))
return refreshing
},
})
Anyone who views the page source can copy the token in it and use it from anywhere until it expires. A browser token can only read what your website already shows, for an hour. A website token could submit enquiries, reviews and orders as your website for fifteen days. If the API Access Token or a website token leaks, regenerate the API Access Token in Gorilla Dash; that revokes every website token and browser token issued with it within a minute.
What a browser token is limited to
Because anyone can copy a browser token, Gorilla Dash limits what it can ask for. Your server's website token has none of these limits.
- One request may batch at most 10 queries. A larger batch is refused with the error code
WEBSITE_TOKEN_BATCH_TOO_LARGE. - Gorilla Dash may also limit how many queries each visitor can run a minute, counting every query in a batch. Past that limit it answers with HTTP 429, the error code
WEBSITE_TOKEN_THROTTLEDand aRetry-Afterheader giving the seconds to wait. reviewsandrangesreturn at most 100 rows, even whencountorresult_countis missing or larger. Your server's website token still gets every row when you leave them out.- A few values meant for your server read as
null: a product'ssupplierandidentifier, and a job posting's salary when you have chosen not to show it. TheproductSuppliersquery is refused. Run those queries on your server with the website token.
Send enquiries and forms through your server
A browser token cannot run mutations, so enquiries, form responses, reviews, sign-ins and orders go from the visitor's browser to your own server, and your server sends them to Gorilla Dash with the website token. Your server is also the place to check the submission, apply your own rate limit and add a CAPTCHA if your site needs one.
// On your server. The browser posts the enquiry form here.
app.post('/enquiry', async (request, reply) => {
const response = await fetch('https://graphql.gorilladash.com/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${await websiteAccessToken()}`,
'User-Agent': 'example-website/1.0',
},
body: JSON.stringify({ query: SUBMIT_ENQUIRY_MUTATION, variables: request.body }),
})
if (!response.ok) return reply.status(502).send({ ok: false })
const result = await response.json()
return reply.status(result.errors?.length ? 422 : 200).send({ ok: !result.errors?.length })
})
SUBMIT_ENQUIRY_MUTATION stands for the submitEnquiry mutation with the fields your form collects; the GraphQL reference lists them.
Render a website page
Pages you build in Gorilla Dash under your website are fetched by their slug with websitePage. The usual approach is to read the last part of the address, ask for that page, and put its fields into your own layout. When the slug is left out, the API returns the first page in your menu order, which is normally the home page.
const client = GorillaDash.createClient({
accessToken: () => window.websiteAccessToken,
})
const PAGE_QUERY = `
query Page($slug: String, $templateSlug: String) {
websitePage(slug: $slug, template_slug: $templateSlug) {
name
slug
meta_title
meta_description
no_index
body
contents {
name
type
value
media_collection {
name
media { default banner square alt_tag }
}
}
}
}
`
// "/about" is the page "about"; "/services/signage" is the page "signage"
// created from the page template "services".
function pageAddress(pathname) {
const segments = pathname.split('/').filter(Boolean)
return {
slug: segments.at(-1) || null,
templateSlug: segments.length > 1 ? segments.at(-2) : null,
}
}
async function renderPage() {
const { websitePage: page } = await client.query(
PAGE_QUERY,
pageAddress(window.location.pathname)
)
if (!page) {
await showMissingPage()
return
}
document.title = page.meta_title || page.name
document.querySelector('meta[name="description"]')
?.setAttribute('content', page.meta_description || '')
document.querySelector('#page-title').textContent = page.name
document.querySelector('#page-body').innerHTML = page.body || ''
}
renderPage().catch(() => {
document.querySelector('#page-body').textContent =
'This page could not be loaded. Please try again shortly.'
})
A page's address in Gorilla Dash is /slug, or /template-slug/slug for pages created from a page template. Pages from different templates can share a slug, so pass the template slug too whenever the address has one, as pageAddress does. If your site adds its own prefix to every address, such as a language code, remove it before calling pageAddress. Addresses under your tribe, product, category or range base paths (see Tribes and locations) are not website pages: route those to the matching query (tribe, product, productCategory or ranges, each by slug) before falling back to websitePage. websitePage returns null rather than an error when no page has that slug; handle that case instead of showing an empty layout. To show tribe-specific versions of a page, pass tribe_slug as well; the API falls back to the organisation page when the tribe has none.
body, and the value of a Rich Text field, are HTML written by your team in the Gorilla Dash editor, including any allowed video embeds. Insert them as HTML only when they come from your own website's Gorilla Dash endpoint. Insert every other field, such as names, headings and labels, as text with textContent. If your site uses a strict Content Security Policy or you want a second line of defence, pass the HTML through a sanitiser such as DOMPurify before inserting it.
Content fields and images
Besides the body, a page carries the content fields defined by its template in contents, in the order they appear in Gorilla Dash. Find a field by its name and read it according to its type:
| Field type | How to read it |
|---|---|
Short Text, Long Text, Date, Switch Input, SelectOne | Use value as text. |
Rich Text | value is HTML. Treat it like the page body. |
SelectMultiple, SelectManually, SelectMeta, ManualList | value is a JSON string. Parse it with JSON.parse. |
Single Image, Gallery | value is null. Read the images from media_collection. |
Each image offers several sizes: default (the original upload), thumbnail, square, portrait, rectangle, banner and original_cropped. All are absolute CDN addresses. A size that was never generated is an empty string, so fall back to default.
function field(page, name) {
return page.contents.find((content) => content.name === name)
}
const heading = field(page, 'Heading')
if (heading) document.querySelector('#hero-heading').textContent = heading.value
const heroImage = field(page, 'Hero Image')?.media_collection[0]?.media[0]
if (heroImage) {
const image = document.querySelector('#hero-image')
image.src = heroImage.banner || heroImage.default
image.alt = heroImage.alt_tag || ''
}
const features = field(page, 'Features')
const featureList = features?.value ? JSON.parse(features.value) : []
The field names above are examples. Use the names your page template defines; you can see them on the page's edit screen in Gorilla Dash. Page-builder layouts are not yet available through the API, so pages you want to render on your own site should use template content fields and the body.
Missing pages and redirects
When websitePage returns null, check the redirects managed in Gorilla Dash before showing a "page not found" message. websiteRedirects returns every redirect as a from and to pair, with redirect loops already left out.
A from value is a pattern, not always a plain path. Besides literal paths such as old-offers, it can contain a named part (:slug), a wildcard (*path) or an optional wildcard ({/*path}), and to can reuse those names. Only those three shapes are supported; other pattern syntax is not supported and may not redirect. Gorilla Dash websites match redirects with the path-to-regexp library (version 8), after lower-casing the address and removing its leading and trailing slashes. Match the same way so your site follows the same rules. The helper below also passes a full https://… target through unchanged, for rules that send visitors to another website:
import { compile, match } from 'path-to-regexp' // version 8
const PATTERN_PART = /\{\/\*\w+\}|\*\w+|:\w+/
function normalise(path) {
let decoded = path
try {
decoded = decodeURIComponent(path)
} catch {
// A stray % is not an escape; keep the path as it is.
}
return decoded.toLowerCase().replace(/^\/+|\/+$/g, '')
}
// "a/{/*rest}" must be written "a{/*rest}" for path-to-regexp.
const joinOptional = (pattern) => pattern.replace(/\/\{\/\*/g, '{/*')
export function resolveRedirect(redirects, pathname) {
const path = normalise(pathname)
for (const { from, to } of redirects) {
try {
const result = match(joinOptional(normalise(from)))(path)
if (!result) continue
if (/^https?:\/\//i.test(to)) return to
if (!PATTERN_PART.test(to)) return '/' + to.replace(/^\/+/, '')
return '/' + compile(joinOptional(normalise(to)))(result.params)
} catch {
// A rule the matcher cannot read never redirects.
}
}
return null
}
In the browser, load path-to-regexp with your bundler, then use the helper when a page is missing:
async function showMissingPage() {
const { websiteRedirects } = await client.query('{ websiteRedirects { from to } }')
const target = resolveRedirect(websiteRedirects, window.location.pathname)
if (target) {
window.location.replace(target)
return
}
document.title = 'Page not found'
document.querySelector('#page-body').textContent =
'Sorry, we could not find that page.'
}
A browser script cannot change the HTTP status of a page that has already loaded, so search engines see the redirect or the missing page only as a normal page. When search ranking matters, apply redirects and return the 404 status on your server, as described in Server rendering and SEO. The API does not store whether a redirect is permanent; choose 301 or 302 on your server.
Menus
Fetch a menu you have built in Gorilla Dash by its name with websiteMenu. The menu is returned as a tree in menu_json: the top item holds the menu's links in children, and every link has a label, a path (site-relative, or the full address for an external link), an absolute url, a url_target for links set to open in a new tab, and its own children for drop-downs.
const { websiteMenu } = await client.query(
'query Menu($name: String) { websiteMenu(name: $name) { menu_json } }',
{ name: 'Main Menu' }
)
function menuList(items = []) {
const list = document.createElement('ul')
for (const item of items) {
const href = item.path || item.url
// Placeholder items group a drop-down and have no address of their own.
const link = document.createElement(href ? 'a' : 'span')
link.textContent = item.label || item.name
if (href) link.href = href
if (href && item.url_target && item.url_target !== '_self') {
link.target = item.url_target
link.rel = 'noopener'
}
const entry = document.createElement('li')
entry.append(link)
if (item.children?.length) entry.append(menuList(item.children))
list.append(entry)
}
return list
}
document.querySelector('#main-menu')
.replaceChildren(menuList(websiteMenu?.menu_json?.children))
The menu name is matched without regard to capitals. websiteMenu returns null when no menu has that name, which the example above renders as an empty list.
Articles
Use articlesPagination for a blog or news list and article for a single article. Only published articles are returned, so drafts and deleted articles never reach your website.
const ARTICLES_QUERY = `
query Articles($page: Int) {
articlesPagination(page: $page, itemsPerPage: 10) {
data {
slug
heading
abstract
created_at
media_collection { media { thumbnail default alt_tag } }
}
current_page
last_page
has_more_pages
}
}
`
const ARTICLE_QUERY = `
query Article($slug: String) {
article(slug: $slug) {
heading
sub_heading
author
created_at
meta_title
meta_description
editor_enabled
article
html
}
}
`
An article's body is HTML, in html when it was written with the visual editor (editor_enabled is true) and in article otherwise. The same HTML guidance as page bodies applies. article returns null for a slug that does not exist or is not published, but returns the most recent article when no slug is passed, so check the slug before running the query. These queries return organisation articles; pass tribe_slug to article for a tribe's article, and use tribeArticlesPagination(tribe_slug: …) for the list a tribe shows, which holds the tribe's own articles plus the organisation's. Use has_more_pages to decide whether to show a "Next page" link.
Tribes and locations
Each tribe (a location, branch or business unit in your organisation) can be listed with tribes or fetched on its own with tribe(slug: …). Only active tribes are listed by default.
const { websiteInfo, tribes } = await client.query(`
{
websiteInfo { base_tribes_path }
tribes {
name
slug
address_1
locality
state
postal_code
main_telephone
opening_hours
}
}
`)
const tribeLinks = tribes.map((tribe) => ({
name: tribe.name,
href: websiteInfo.base_tribes_path + tribe.slug,
}))
opening_hours is returned as JSON: a list of day, open and close entries, so it takes no field selection. websiteInfo returns the path prefixes your website uses for tribe, product, category and range pages (base_tribes_path, base_products_path, base_categories_path, base_ranges_path). Add the item's slug to the prefix to build a link, and check that the prefix ends with / in your website settings so the two join correctly. Products also return a ready-made path. Unlike websitePage, tribe and product return an error rather than null when the slug does not match.
What to query
| To render | Query | Notes |
|---|---|---|
| A page | websitePage(slug) | null when not found. Body is HTML. |
| A list of pages | websitePages(template_slug, type) | Not paginated. |
| Navigation | websiteMenu(name) | Tree in menu_json. |
| Header or footer blocks | websiteSection(name) | Content fields shaped like page contents. |
| Redirects | websiteRedirects | from and to paths. |
| Blog or news list | articlesPagination(page, itemsPerPage) | Published articles only; at most 100 a page. |
| One article | article(slug) | null when not found. |
| Tribes or locations | tribes, tribe(slug), searchStores | Link with base_tribes_path. |
| Products | products, product(slug) | Use the product's path. |
| FAQs | websiteFaq, websiteFaqCategory | |
| Reviews | reviews | |
| Site name, base URL, theme | websiteInfo | Never null. |
The GraphQL reference lists every argument and field for these queries.
Caching and freshness
How quickly an edit in Gorilla Dash appears on your site depends on how your site asks for content:
- The browser client above (
createClient) sends each query as a POST request. These are never cached, so visitors always see the current content, and every page view makes a request to Gorilla Dash. This suits pages with moderate traffic and the parts of a page that must be current. - The Apollo adapter with persisted queries turned on sends GET requests that are cached at Gorilla Dash's edge, so an edit you save normally appears within about five minutes. Data that changes without anyone editing it, such as bookable appointment times, is cached for seconds only. With
persistedQueries: falsethe adapter sends ordinary POST requests, which are not cached. - Server rendering lets you keep your own cache on your server. To empty it when content changes, point the Cache Clear URL in the Website Cache section of your website's Settings at your server and turn on Clear Website cache Automatically; see keeping your website fresh.
For a busy site, render pages on your server and cache them there, and keep the browser client for small interactive pieces. The Apollo adapter is an alternative once you have the @gorilladash/website-sdk module.
Chatbot
The new script includes the chatbot implementation. Existing chat-widget.js installations continue working unchanged. Adding the new script alongside a matching legacy chatbot does not mount a second chatbot.
<script src="https://gorilladash.com/website-sdk.js?v=1"
data-org="your-organisation"
data-chatbot="42"
data-track-attribution="false"
defer></script>
Supported optional attributes: data-tribe, data-expanded, data-preview, data-remember-tribe and data-track-attribution. Attribution tracking defaults to the existing widget behaviour; set it to false to disable it.
For loading after consent, omit the chatbot attributes and start it explicitly:
await GorillaDash.chatbot.load({
org: 'your-organisation',
chatbot: 42,
trackAttribution: false,
})
The promise resolves when the bundled widget starts; visibility is still controlled by the chatbot configuration. One chatbot configuration is supported per page. GorillaDash.ready represents automatic startup, and automatic startup failures dispatch gorilladash:error.
Optional Apollo adapter
For applications already using Apollo, install Apollo Client 4 and GraphQL 16, then import the separate adapter. Vue is not required.
import { createWebsiteApolloClient } from '@gorilladash/website-sdk/apollo'
const apollo = createWebsiteApolloClient({
accessToken: () => window.websiteAccessToken,
organisationId: 'YOUR_ORGANISATION_ID',
websiteId: 'YOUR_WEBSITE_ID',
})
The adapter has an in-memory cache and uses persisted-query GET requests, with a full-query fallback when needed. Supply both IDs for the site's cache namespace. Set persistedQueries: false to use ordinary POST requests.
TypeScript and autocomplete
The website GraphQL schema is published at https://gorilladash.com/graphql/schema.graphql. Point your editor and GraphQL Code Generator at it and you get three things: queries that autocomplete and are checked as you type, a TypeScript type for every result, and a compile error when a query is missing a required variable or passes the wrong type.
Autocomplete in your editor
Add a graphql.config.yml file to the root of your project. The GraphQL extension for VS Code (GraphQL: Language Feature Support) and the GraphQL plugin for JetBrains editors both read it, and then autocomplete field names and flag unknown fields inside your queries.
schema: https://gorilladash.com/graphql/schema.graphql
documents: src/**/*.{ts,tsx,vue}
Typed queries
Install @graphql-codegen/cli and @graphql-codegen/client-preset as development dependencies, and add a codegen.ts file. With documentMode: 'string' the generated documents are plain strings that carry their types, which is what the content client expects. Leave that line out if you use the Apollo adapter, which takes Apollo's own document objects.
import type { CodegenConfig } from '@graphql-codegen/cli'
const config: CodegenConfig = {
schema: 'https://gorilladash.com/graphql/schema.graphql',
documents: ['src/**/*.{ts,tsx,vue}'],
generates: {
'./src/gql/': {
preset: 'client',
config: { documentMode: 'string', useTypeImports: true },
},
},
}
export default config
Run npx graphql-codegen after changing a query, or npx graphql-codegen --watch while you work. Write each query with the generated graphql() function and pass it to the client instead of a string:
import { createWebsiteClient } from '@gorilladash/website-sdk'
import { graphql } from './gql'
const PageQuery = graphql(`
query Page($slug: String!) {
websitePage(slug: $slug) { name meta_title body }
}
`)
const client = createWebsiteClient({ accessToken: () => window.websiteAccessToken })
// websitePage is typed from the schema. Leaving out slug, or passing a
// number, is a compile error.
const { websitePage } = await client.query(PageQuery, { slug: 'about' })
With the Apollo adapter, generate without documentMode: 'string', because Apollo takes document objects rather than strings. The generated document then gives a typed data result: apollo.query({ query: PageQuery, variables: { slug: 'about' } }). A site that uses both clients generates two outputs, one in each mode. If an Apollo document is passed to the content client by mistake, TypeScript flags it, and at run time the client throws "Parsed documents belong with the Apollo adapter" before sending anything. A plain string query still works with either client. Its result is typed as unknown unless you pass the type yourself, as in client.query<MyResult>(`…`).
Server rendering and SEO
A browser script alone does not prerender a page. Return populated HTML from your site's server or static build for search engines and LLM crawlers. Hydrate that HTML in the browser and use the JavaScript SDK for subsequent content requests.
Laravel sites can install the separate Laravel website SDK for server-side queries and caching, and use Inertia SSR to render their Vue pages. Other stacks can use their own server-rendering tools. Create a separate Apollo client for every SSR request and restore its public content cache in the browser with initialState. Do not serialize private credentials or share visitor state between requests.
Server rendering with the Apollo adapter
Create a new Apollo client for every request, so one visitor's data can never reach another. On the server it uses the website token. The browser client then starts from the server's cache and switches to the browser token for anything it fetches later.
// On your server, once per request.
import { createWebsiteApolloClient } from '@gorilladash/website-sdk/apollo'
import { websiteAccessToken, browserAccessToken } from './gorilla-dash-token.js'
import { PageQuery } from './queries.js'
export async function renderPage(slug) {
const apollo = createWebsiteApolloClient({
accessToken: websiteAccessToken,
organisationId: 'YOUR_ORGANISATION_ID',
websiteId: 'YOUR_WEBSITE_ID',
ssrMode: true,
})
const { data } = await apollo.query({ query: PageQuery, variables: { slug } })
// Escape "<" so neither value can close the script element early.
const script = (value) => JSON.stringify(value).replace(/</g, '\\u003c')
return `${renderYourApp(data)}
<script>
window.__GORILLA_DASH_STATE__ = ${script(apollo.extract())}
window.websiteAccessToken = ${script(await browserAccessToken())}
</script>`
}
// In the browser.
const apollo = createWebsiteApolloClient({
accessToken: () => window.websiteAccessToken,
organisationId: 'YOUR_ORGANISATION_ID',
websiteId: 'YOUR_WEBSITE_ID',
initialState: window.__GORILLA_DASH_STATE__,
})
Everything in the cache is written into the page, so run only public content queries on a client whose cache you send to the browser. A visitor's sign-in, cart or order belongs on a separate client that is never extracted. renderYourApp stands for your framework's own render call; Vue, React and other frameworks each have one that runs the queries on the server first. If a page can stay open for longer than an hour, give the browser client the refreshing accessToken function from Authentication.
Server rendering uses the same queries as the browser examples. This Node sketch renders a page, applies Gorilla Dash redirects and returns a real 404 status; adapt it to your framework's request and response objects.
import { websiteAccessToken } from './gorilla-dash-token.js'
import { resolveRedirect } from './gorilla-dash-redirects.js'
async function gorillaDashQuery(query, variables = {}) {
const response = await fetch('https://graphql.gorilladash.com/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${await websiteAccessToken()}`,
'User-Agent': 'example-website/1.0',
},
body: JSON.stringify({ query, variables }),
})
const result = await response.json()
if (!response.ok || result.errors?.length) {
throw new Error('Gorilla Dash content request failed')
}
return result.data
}
export async function renderRequest(request, reply) {
const path = new URL(request.url, 'https://example.com').pathname
// Route tribe, product, category and range addresses to their own
// queries here, before treating the address as a website page.
let page
let websiteRedirects = []
try {
;({ websitePage: page } = await gorillaDashQuery(PAGE_QUERY, pageAddress(path)))
if (!page) {
;({ websiteRedirects } = await gorillaDashQuery('{ websiteRedirects { from to } }'))
}
} catch {
return reply.status(503).send(renderUnavailable())
}
if (!page) {
const target = resolveRedirect(websiteRedirects, path)
return target
? reply.redirect(301, target) // Fastify 4 order; Fastify 5 takes (target, 301)
: reply.status(404).send(renderNotFound())
}
return reply.type('text/html').send(`<!doctype html>
<html lang="en">
<head>
<title>${escapeHtml(page.meta_title || page.name)}</title>
<meta name="description" content="${escapeHtml(page.meta_description || '')}">
${page.no_index ? '<meta name="robots" content="noindex">' : ''}
</head>
<body>
<h1>${escapeHtml(page.name)}</h1>
<main>${page.body || ''}</main>
</body>
</html>`)
}
PAGE_QUERY and pageAddress are the ones from Render a website page, and resolveRedirect is the helper from Missing pages and redirects. escapeHtml, renderNotFound and renderUnavailable stand for your own helpers. escapeHtml must escape &, <, >, " and ', because it is also used inside attribute values. Escape every text field; only the page body and Rich Text values are inserted as HTML.
Errors and options
| Option | Purpose |
|---|---|
accessToken | Required. A browser token, or a function returning one. The function receives { forceRefresh }, which is true after Gorilla Dash has refused the previous token. |
endpoint | Defaults to https://graphql.gorilladash.com/graphql. |
timeoutMs | Request timeout in milliseconds; defaults to 15000. |
fetch | Optional custom Fetch implementation. |
The content client rejects HTTP failures, GraphQL errors, invalid responses and timeouts. GraphQL errors use the name GorillaDashQueryError and include an errors array. Handle failures in your site's UI. Browser requests omit cookies and reject redirects.
A query that a browser token is not allowed to run returns a GraphQL error whose extensions.code is WEBSITE_TOKEN_READ_ONLY, naming the fields it refused; run that query from your server instead. WEBSITE_TOKEN_UNVERIFIED means Gorilla Dash could not check the token. The SDK does not retry on either code, because neither is fixed by a new token; if you see WEBSITE_TOKEN_UNVERIFIED, contact Gorilla Dash support. A browser token query is also limited to 500 selected fields, which is well above what a page needs; split a larger query in two.