@financial-times/dotcom-ui-app-context

This package provides methods for embedding app context data into your server-side rendered pages and safely retrieving it again in the browser.

Usage no npm install needed!

<script type="module">
  import financialTimesDotcomUiAppContext from 'https://cdn.skypack.dev/@financial-times/dotcom-ui-app-context';
</script>

README

@financial-times/dotcom-ui-app-context

This package provides methods for embedding app context data into your server-side rendered pages and safely retrieving it again in the browser.

If you want to share application specific data with the client, consider using @financial-times/dotcom-ui-data-embed.

Getting started

This package is compatible with Node 12+ and is distributed on npm.

npm install --save @financial-times/dotcom-ui-app-context

After installing the package you can use it to embed app-context data into your pages on the server-side. This data can then be retrieved and used in your client-side code.

Server-side integration

If you are using React to render your app you can use the AppContextEmbed component to integrate the app context data with your pages:

import { AppContextEmbed } from '@financial-times/dotcom-ui-app-context'
const appContext = { appName: 'app-name', contextProperty: 'my-property' }

export default (props) => (
  <html>
    <head>
      <meta charSet="utf-8" />
      <title>My Amazing Website</title>
    </head>
    <body>
      ...
      <AppContextEmbed appContext={appContext} />
    </body>
  </html>
)

Otherwise you can insert a JSON formatted string into a <script> element with an ID of page-kit-app-context.

function page() {
  return `<!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>My Amazing Website</title>
    </head>
    <body>
      ...
      <script type="application/json" id="page-kit-app-context">
        {"appName":"app-name","contextProperty":"my-property"}
      </script>
    </body>
  </html>`
}

Client-side integration

Once you are delivering the app context data with your pages you can use the app context client in your client-side code. The client provides methods for safely retrieving the status of individual context properties.

import * as appContext from '@financial-times/dotcom-ui-app-context'

const appContext = appContext.init()

if (appContext.get('my-context-property')) {
  ...
}

Client-side API

init()

Initialises and returns a new app context client which can be used to safely access the status of individual contexts.

App context client API

get(property: string)

Returns the value of the requested property. If the property is not found this will return undefined.

getAll()

Returns all app context data.

Please note that the app context data object is frozen so it cannot be modified.