Skip to content

Instantly share code, notes, and snippets.

@kevinxh
Last active January 18, 2025 02:23
Show Gist options
  • Save kevinxh/a760016a1a7635a9a731904590461aa8 to your computer and use it in GitHub Desktop.
Save kevinxh/a760016a1a7635a9a731904590461aa8 to your computer and use it in GitHub Desktop.
PWA Kit SDK interface documentation (v3.8)

version: v3.8

packages:

  • @salesforce/pwa-kit-runtime
  • @salesforce/pwa-kit-react-sdk

@salesforce/pwa-kit-runtime/ssr/server/express

@salesforce/pwa-kit-runtime/ssr/server/express.getRuntime ⇒ Object

Get the appropriate runtime object for the current environment (remote or development)

getRuntime().render(req, res, next) ⇒ Promise.<void>

This is the main react-rendering function for SSR. It is an Express handler that performs server-side rendering of the React application.

The function follows these main steps:

  1. Matches the requested URL to a route
  2. Loads the React component for that route
  3. Initializes the application state
  4. Renders the React application to HTML
  5. Sends the response with appropriate status code and headers

Kind: static method of @salesforce/pwa-kit-react-sdk/ssr/server/react-rendering Returns: Promise.<void> - Resolves when rendering is complete Throws:

  • Error Unrecoverable errors are passed to Express error handling
Param Type Description
req Object Express request object
res Object Express response object
next function Express next middleware function

Example

import {getRuntime} from '@salesforce/pwa-kit-runtime/ssr/server/express'
const runtime = getRuntime()
app.get('*', runtime.render)

@salesforce/pwa-kit-runtime/utils/ssr-server

@salesforce/pwa-kit-runtime/utils/ssr-server.isRemote() ⇒ boolean

Determines if the current environment is running in AWS Lambda

Kind: static method of @salesforce/pwa-kit-runtime/utils/ssr-server Returns: boolean - True if running in AWS Lambda, false otherwise Example

import {isRemote} from '@salesforce/pwa-kit-runtime/utils/ssr-server'

if (isRemote()) {
  console.log('Running in AWS Lambda')
} else {
  console.log('Running in development environment')
}

@salesforce/pwa-kit-runtime/utils/ssr-config

@salesforce/pwa-kit-runtime/utils/ssr-config.getConfig() ⇒ Object

Returns the app configuration object.

Kind: static method of @salesforce/pwa-kit-runtime/utils/ssr-config Returns: Object - The application configuration object

Example

import {getConfig} from '@salesforce/pwa-kit-runtime/utils/ssr-config'
const config = getConfig()
console.log(config)

@salesforce/pwa-kit-runtime/utils/logger-factory

@salesforce/pwa-kit-runtime/utils/logger-factory~createLogger(config) ⇒ PWAKitLogger

Create a logger instance for each package.

Kind: inner method of @salesforce/pwa-kit-runtime/utils/logger-factory Returns: PWAKitLogger - - An instance of PWAKitLogger configured for the specified package.

Param Type Description
config Object Configuration object for the logger.
config.packageName string The name of the package where the logger is used.

Example

import createLogger from '@salesforce/pwa-kit-runtime/utils/logger-factory'

const logger = createLogger({
  packageName: '@salesforce/pwa-kit-runtime'
})

logger.info('Server started')
logger.error('Failed to connect', {error: err})

@salesforce/pwa-kit-runtime/utils/middleware

@salesforce/pwa-kit-runtime/utils/middleware.defaultPwaKitSecurityHeaders

This express middleware sets the Content-Security-Policy and Strict-Transport-Security headers to default values that are required for PWA Kit to work. It also patches res.setHeader to allow additional CSP directives to be added without removing the required directives, and it prevents the Strict-Transport-Security header from being set on the local dev server.

Kind: static constant of @salesforce/pwa-kit-runtime/utils/middleware

Param Type Description
req express.Request Express request object
res express.Response Express response object
next express.NextFunction Express next callback

Example

import {defaultPwaKitSecurityHeaders} from '@salesforce/pwa-kit-runtime/utils/middleware'

// Add security headers middleware to Express app
app.use(defaultPwaKitSecurityHeaders)

@salesforce/pwa-kit-react-sdk/ssr/browser/main

@salesforce/pwa-kit-react-sdk/ssr/browser/main.registerServiceWorker ⇒ Promise

Register a service worker for the application. This function will wait for the page to load before attempting to register the service worker.

Kind: static constant of @salesforce/pwa-kit-react-sdk/ssr/browser/main Returns: Promise - A promise that resolves when registration is complete

Param Type Description
url string The URL of the service worker script to register

Example

import {registerServiceWorker} from '@salesforce/pwa-kit-react-sdk/ssr/browser/main'

// Register service worker
registerServiceWorker('/worker.js')
  .then(() => console.log('Service worker registered'))
  .catch(err => console.error('Service worker registration failed:', err))

@salesforce/pwa-kit-react-sdk/ssr/browser/main.start ⇒ Promise

Starts the PWA Kit application in the browser by hydrating the server-rendered content. This function handles setting up the application state, and performing the hydration process.

Kind: static constant of @salesforce/pwa-kit-react-sdk/ssr/browser/main Returns: Promise - A promise that resolves when the application has been hydrated Example

import {start} from '@salesforce/pwa-kit-react-sdk/ssr/browser/main'

// Start the application
start().then(() => {
  console.log('Application started successfully')
})

@salesforce/pwa-kit-react-sdk/ssr/universal/utils

@salesforce/pwa-kit-react-sdk/ssr/universal/utils.getAssetUrl(path) ⇒ string

Get the URL that should be used to load an asset from the bundle.

Kind: static method of @salesforce/pwa-kit-react-sdk/ssr/universal/utils

Param Type Description
path string relative path from the build directory to the asset

Example

import {getAssetUrl} from '@salesforce/pwa-kit-react-sdk/ssr/universal/utils'

// Get URL for an image asset
const imageUrl = getAssetUrl('images/logo.png')

@salesforce/pwa-kit-react-sdk/ssr/universal/utils.getProxyConfigs() ⇒ Array.<ProxyConfig>

Return the set of proxies configured for the app.

The result is an array of objects, each of which has 'protocol' (either 'http' or 'https'), 'host' (the hostname) and 'path' (the path element that follows "/mobify/proxy/", defaulting to 'base' for the first proxy, and 'base2' for the next).

Kind: static method of @salesforce/pwa-kit-react-sdk/ssr/universal/utils Example

import {getProxyConfigs} from '@salesforce/pwa-kit-react-sdk/ssr/universal/utils'

// Get configured proxies
const proxies = getProxyConfigs()
// Example output:
// [
//   {protocol: 'https', host: 'example.com', path: 'base'},
//   {protocol: 'https', host: 'api.example.com', path: 'base2'}
// ]

@salesforce/pwa-kit-react-sdk/ssr/universal/utils~ProxyConfig : Object

Kind: inner typedef of @salesforce/pwa-kit-react-sdk/ssr/universal/utils Properties

Name Type Description
protocol String http or https
host String the hostname
path String the path element that follows "mobify/proxy"

@salesforce/pwa-kit-react-sdk/ssr/universal/hooks

@salesforce/pwa-kit-react-sdk/ssr/universal/hooks.useCorrelationId ⇒ object

Use this hook to get the correlation id value of the closest CorrelationIdProvider component.

Kind: static constant of @salesforce/pwa-kit-react-sdk/ssr/universal/hooks Returns: object - The correlation id Example

import {useCorrelationId} from '@salesforce/pwa-kit-react-sdk/ssr/universal/hooks'

// Get correlation id
const correlationId = useCorrelationId()
console.log(correlationId)

@salesforce/pwa-kit-react-sdk/ssr/universal/hooks.useServerContext ⇒ ServerContext

Get the server context

Kind: static constant of @salesforce/pwa-kit-react-sdk/ssr/universal/hooks Returns: ServerContext - ServerContext object Example

import {useServerContext} from '@salesforce/pwa-kit-react-sdk/ssr/universal/hooks'

// Get server context
const {res} = useServerContext()
if (res && query.error) { res.status(404) }

@salesforce/pwa-kit-react-sdk/ssr/universal/hooks.useOrigin ⇒ string

Returns the application's origin.

By default, it will return the ORIGIN under which we are serving the page.

If fromXForwardedHeader is true, it will use the value of x-forwarded-proto and x-forwarded-host headers in req to build origin. (it is false by default)

NOTE: this is a React hook, so it has to be used in a React rendering pipeline.

Kind: static constant of @salesforce/pwa-kit-react-sdk/ssr/universal/hooks Returns: string - origin string Example

import {useOrigin} from '@salesforce/pwa-kit-react-sdk/ssr/universal/hooks'

// Get origin
const origin = useOrigin()
console.log(origin)
// https://example.com

@salesforce/pwa-kit-react-sdk/ssr/universal/hooks~ServerContext : Object

Server context

Kind: inner typedef of @salesforce/pwa-kit-react-sdk/ssr/universal/hooks Properties

Name Type Description
req Object Request object
res Object Response object

@salesforce/pwa-kit-react-sdk/ssr/universal/errors

@salesforce/pwa-kit-react-sdk/ssr/universal/errors~HTTPError ⇐ Error

Kind: inner class of @salesforce/pwa-kit-react-sdk/ssr/universal/errors Extends: Error

new HTTPError(status, message)

Param Type Description
status number The HTTP status code
message string The error message

Example

import {HTTPError} from '@salesforce/pwa-kit-react-sdk/ssr/universal/errors'

// Create an HTTPError
const error = new HTTPError(404, 'Not Found')
console.log(error.message)
// Not Found

@salesforce/pwa-kit-react-sdk/ssr/universal/errors~HTTPNotFound ⇐ HTTPError

Kind: inner class of @salesforce/pwa-kit-react-sdk/ssr/universal/errors Extends: HTTPError

new HTTPNotFound(message)

Param Type Description
message string The error message

Example

import {HTTPNotFound} from '@salesforce/pwa-kit-react-sdk/ssr/universal/errors'

// Create an HTTPNotFound error
const error = new HTTPNotFound('Not Found')
console.log(error.message)
// Not Found

@salesforce/pwa-kit-react-sdk/ssr/universal/components/with-react-query

@salesforce/pwa-kit-react-sdk/ssr/universal/components/with-react-query.withReactQuery ⇒ React.ReactElement

A HoC for adding React Query support to your application. Wrap your AppConfig component with this HOC to enable React Query support.

Kind: static constant of @salesforce/pwa-kit-react-sdk/ssr/universal/components/with-react-query

Param Type Description
Wrapped React.ReactElement The component to be wrapped
options Object
options.queryClientConfig Object The react query client configuration object to be used.
options.beforeHydrate function A function that will be called before the component is hydrated. It will receive the preloaded state and return the state to be hydrated.

Example

import {withReactQuery} from '@salesforce/pwa-kit-react-sdk/ssr/universal/components/with-react-query'

// Wrap a component with React Query
const WrappedComponent = withReactQuery(AppConfig)

@salesforce/pwa-kit-react-sdk/ssr/universal/components/with-legacy-get-props

@salesforce/pwa-kit-react-sdk/ssr/universal/components/with-legacy-get-props.withLegacyGetProps ⇒ React.ReactElement

A HoC for adding legacy getProps support to your application. Wrap your AppConfig component with this HOC to enable legacy getProps support.

Kind: static constant of @salesforce/pwa-kit-react-sdk/ssr/universal/components/with-legacy-get-props

Param Type Description
Wrapped React.ReactElement The component to be wrapped

Example

import {withLegacyGetProps} from '@salesforce/pwa-kit-react-sdk/ssr/universal/components/with-legacy-get-props'

// Wrap a component with legacy getProps
const WrappedComponent = withLegacyGetProps(AppConfig)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment