JavaScript SDK reference for headless Optimizely Forms
The headless Optimizely Forms JavaScript SDK enables front-end apps to load, validate, and submit forms from Optimizely Content Management System (CMS) 13. It provides ready-made models for forms and fields, API clients that fetch forms and send submissions, and helpers that handle common tasks like choosing the right field to display.
Use this reference when you build a custom form renderer instead of using the React components.
The SDK has two packages:
- @episerver/forms-sdk – Models, API clients, validators, and step helpers. Works with any JavaScript framework.
- @episerver/forms-react – React components that render forms. Depends on @episerver/forms-sdk.
To render forms with the ready-made Form component, see Render headless Optimizely Forms in a React app.
Form models
The Forms REST API returns form data in camelCase JSON. The SDK models match this structure.
The FormContainer model describes a form:
- key – The key that identifies the form.
- properties – Form settings, such as title, allowAnonymousSubmission, and submitSuccessMessage.
- formElements – The elements in the form.
- steps – The form elements grouped by step. StepBuilder fills this property.
- locale – The language of the form.
- localizations – Localized form messages, such as the error message for a visitor who must sign in.
Each element in formElements has the following properties:
- key – The key that identifies the element. Submissions use this key for the element value.
- contentType – The element type, such as TextboxElementBlock or SubmitButtonElementBlock.
- displayName – The element name in CMS.
- properties – Element settings, such as label, placeHolder, and validators.
- localizations – Localized element text, such as button labels.
Each validator in an element's validators list has a type, such as RequiredValidator, and a model with the validation message.
React components
The @episerver/forms-react package provides the following components:
- Form – Loads a form by key from the API and renders it.
- FormContainerBlock – Renders a form from a FormContainer object that you already loaded.
- FormLogin – Renders a sign-in form that requests an access token for submissions.
The Form and FormContainerBlock components store their state in FormContext, a React context. The state includes the form metadata, the values that the visitor enters, and the validation results.
FormAuthenticate
FormAuthenticate requests an access token from the OpenID Connect (OIDC) token endpoint with a user name and password. Use it to sign in visitors from a custom sign-in form. The Forms API requires a token to accept a submission.
login(username, password) returns a promise that resolves to the access token. The promise rejects when the token endpoint returns an error.
The following example uses the class:
const formAuthenticate = new FormAuthenticate({
clientId: "FRONTEND_CLIENT_ID",
grantType: "password",
authBaseUrl: "https://cms.example.com/api/episerver/connect/token",
});
const accessToken = await formAuthenticate.login(username, password);FormCache
FormCache saves, reads, and removes values in browser storage. Use it to keep values, such as the access token, across page reloads. By default, it uses sessionStorage. FormLogin uses FormCache to keep the access token under the FormConstants.FormAccessToken key.
The class has the following methods:
- get<T>(key) – Returns the value saved under the key.
- set<T>(key, data) – Saves the value under the key.
- remove(key) – Removes the value saved under the key.
The following example uses the class:
const formCache = new FormCache();
formCache.set("KEY", "VALUE");
const value = formCache.get<string>("KEY");
formCache.remove("KEY");Note Keep access tokens in sessionStorage. Do not pass window.localStorage to a FormCache that stores tokens, because values in localStorage persist after the browser closes.
FormDependConditions
FormDependConditions checks whether an element's display conditions are met, based on the values of other elements. Use it to show or hide elements as the visitor fills in the form.
checkConditions(formSubmissions) returns true when the element's conditions are met.
The following example uses the class:
const formDependConditions = new FormDependConditions(formElement);
// formSubmissions is an array of { elementKey, value } objects.
const isSatisfied = formDependConditions.checkConditions(formSubmissions);FormLoader
FormLoader gets a form from the Forms API, so a custom renderer can display a form that editors published.
getForm(key, language) returns a promise that resolves to a FormContainer object.
Pass the base URL of the CMS site in the baseURL property. End the URL with a slash.
const formLoader = new FormLoader({ baseURL: "https://cms.example.com/" });
const form = await formLoader.getForm(formKey, "en");FormStorage
FormStorage saves a form's submission data in sessionStorage so a visitor keeps their input between steps of a multi-step form.
The class has the following methods:
- saveFormDataToStorage(data) – Saves an array of FormSubmission objects.
- loadFormDataFromStorage() – Returns the saved FormSubmission objects.
- removeFormDataInStorage() – Removes the saved data for the form.
The following example uses the class:
const formStorage = new FormStorage(formContainer);
formStorage.saveFormDataToStorage(formSubmissions);
const savedSubmissions = formStorage.loadFormDataFromStorage();
formStorage.removeFormDataInStorage();FormSubmitter
FormSubmitter validates submission data and sends it to the Forms API with a PUT request. Use it to submit a form from a custom renderer.
The class has the following methods:
- doValidate(formSubmissions) – Validates each value and returns an array of FormValidationResult objects.
- doSubmit(model) – Submits the data. Returns a promise that resolves to a FormSubmitResult object, or rejects with a ProblemDetail object.
The doSubmit model has the following properties:
- formKey – The key of the form.
- locale – The language of the form.
- submissionData – An array of FormSubmission objects with an elementKey and a value.
- isFinalized – Set to true on the last step to complete the submission.
- partialSubmissionKey – The submissionKey that the previous step returned. Use an empty string on the first step.
- hostedPageUrl – The URL of the page that displays the form.
- accessToken – The visitor's access token.
- currentStepIndex – The zero-based index of the submitted step.
The following example uses the class:
const formSubmitter = new FormSubmitter(formContainer, "https://cms.example.com/");
const validationResults = formSubmitter.doValidate(formSubmissions);
try {
const result = await formSubmitter.doSubmit({
formKey: formContainer.key,
locale: formContainer.locale,
submissionData: formSubmissions,
isFinalized: true,
partialSubmissionKey: "",
hostedPageUrl: window.location.href,
accessToken: accessToken,
currentStepIndex: 0,
});
// Handle the result.
} catch (problem) {
// Handle the error.
}FormValidator
FormValidator validates an element value against the validators in the element's metadata, such as RequiredValidator and EmailValidator. Use it to show validation messages before the visitor submits.
The class has the following methods:
- validate(value) – Runs the element's validators in order and stops at the first failure. Returns an ElementValidationResult object with valid and message properties.
- validateRequired(value) – Returns true when the value is not empty.
- validateRegex(value, model) – Returns true when the value matches the validator's pattern.
- validateFileExtension(value, model) – Returns true when each file has an allowed extension.
- validateFileSize(value, model) – Returns true when each file is within the size limit.
- validateNumeric(value) – Returns true when the value is a number.
The following example uses the class:
const formValidator = new FormValidator(formElement);
const result = formValidator.validate(value);
if (!result.valid) {
console.log(result.message);
}StepBuilder
StepBuilder groups a form's elements by step, so you can render a multi-step form one step at a time.
buildForm() returns a copy of the form with its steps property filled. Each step has a formStep and the elements in that step.
The following example uses the class:
const stepBuilder = new StepBuilder(formContainer);
// Get the form with its elements grouped by step.
const form = stepBuilder.buildForm();StepDependCondition
StepDependCondition finds the next or previous step to display. When a step depends on an element value, the class checks the condition. It skips steps whose conditions are not met.
The class has the following methods:
- isSatisfied(stepIndex) – Returns true when the step's condition is met.
- findNextStep(currentStepIndex) – Returns the index of the next step to display.
- findPreviousStep(currentStepIndex) – Returns the index of the previous step to display.
- isStepValidToDisplay(stepIndex, currentPageUrl) – Returns true when the step can display on the current page.
- getInactiveStepsIndex() – Returns the indexes of steps whose conditions are not met.
The following example uses the class:
// inactiveElements is an array of keys of elements whose conditions are not met.
const stepDependCondition = new StepDependCondition(formContainer, inactiveElements);
const nextStepIndex = stepDependCondition.findNextStep(currentStepIndex);
const previousStepIndex = stepDependCondition.findPreviousStep(currentStepIndex);StepHelper
StepHelper provides helper methods for multi-step forms, such as finding the current step or a step's first invalid element.
The class has the following methods:
- isAllStepsAreNotLinked() – Returns true when no step is attached to a page.
- isMalFormSteps() – Returns true when some steps are attached to a page and others are not.
- getCurrentStepIndex(currentPageUrl) – Returns the index of the step for the current page.
- isInCurrentStep(elementKey, stepIndex) – Returns true when the element belongs to the step.
- getFirstInvalidElement(formValidationResults, stepIndex) – Returns the key of the first element in the step that failed validation.
- getFirstInputElement(stepIndex, inactiveElements) – Returns the key of the first active input element in the step.
- isNeedCheckDependCondition(stepIndex) – Returns true when the step has a condition to check.
The following example uses the class:
const stepHelper = new StepHelper(formContainer);
const stepIndex = stepHelper.getCurrentStepIndex(window.location.href);Helper functions
Use the following functions in a custom renderer to get the same initial values and state as the React components:
- getDefaultValue(element) – Returns the element's default value, such as its predefined value or its preselected items.
- initFormState(formContainer, currentPageUrl, history) – Returns the initial FormState object for a form.
Element types
The SDK defines a model for each Optimizely Forms element:
- Textbox – A single line of text.
- Textarea – Several lines of text.
- Number – A numeric value.
- Range – An integer within a range.
- Url – A URL.
- Selection – A drop-down list or a list box, based on the allowMultiSelect property.
- Choice – Radio buttons or checkboxes, based on the allowMultiSelect property.
- ImageChoice – A choice between images.
- FileUpload – Files to include in the submission.
- ParagraphText – Rich text that can include placeholders.
- PredefinedHidden – A hidden field with a predefined value.
- VisitorDataHidden – A hidden field that collects visitor data, such as the IP address or browser.
- FormStep – The end of a form step.
- SubmitButton – A button that submits the form.
- ResetButton – A button that clears the form.
The element models inherit from the following base types:
- FormElementBase – The base type for every element.
- ValidatableElementBase – Elements that support validators.
- DataElementBlockBase – Elements that collect data and support field mapping.
- InputElementBase – Input elements.
- SelectionBase – Elements with a list of options.
- ButtonBase – Button elements.
- HiddenElementBase – Hidden elements.
Note The Forms API does not support captcha elements, such as reCAPTCHA or hCaptcha.
Other types
The SDK also defines the following types for conditions, validation, state, and errors:
- Condition and ConditionProperties – Display conditions for an element.
- ConditionCombinationType – Whether all conditions or any condition must be met.
- ConditionFunctionType – The operator that a condition uses to compare values.
- SatisfiedActionType – Whether to show or hide an element when its conditions are met.
- SubmitButtonType – The type of step navigation button.
- ValidatorType – The validator types.
- FormConstants – The keys of values that the SDK caches.
- FormState – The state that FormContext stores.
- FormSubmission – A submitted element value.
- FormValidationResult and ElementValidationResult – Validation results.
- IdentityInfo – The visitor's access token and user name.
- ProblemDetail – An error response from the API.