Render headless Optimizely Forms in a React app
Render forms from Optimizely Content Management System (CMS) 13 in a React app with the headless Optimizely Forms JavaScript SDK. The Form component loads a form from the Forms REST API, renders its elements, validates input, and submits it. Editors change the form in CMS, and the app displays the change without a new build.
Prerequisites
You need the following to build the app:
- A CMS 13 site with the headless Forms API. For API configuration instructions, see Set up the headless Optimizely Forms API.
- A published form and its form key. The form key is the form's content globally unique identifier (GUID), without hyphens.
- The client ID of the OpenID Connect (OIDC) application that you registered for the front end.
- Node.js and npm. Use a Node.js version that your React build tool supports.
Create the React app
The following steps use Vite to create a TypeScript React app. The SDK's sample-react-app uses React 18 and React Router 5, and this page uses the same versions.
- Create the app:
npm create vite@latest headless-form -- --template react-ts- Go to the app folder:
cd headless-form- Install React 18:
npm install react@18 react-dom@18
npm install --save-dev @types/react@18 @types/react-dom@18- Point npm to the feed that hosts the @episerver packages. Create an .npmrc file in the app folder with the following line:
@episerver:registry=https://pkgs.dev.azure.com/EpiserverEngineering/netCore/_packaging/HeadlessForms/npm/registry/- Install the SDK packages and React Router 5:
npm install @episerver/forms-sdk @episerver/forms-react [email protected]
npm install --save-dev @types/react-router-dom@5The Form component reads navigation from the history object of React Router 5. React Router 6 and later do not provide this object.
Configure the app
Connect the app to your CMS site and choose the form to display. Vite reads these settings when the app starts.
- Create an .env file in the app folder with the following content:
VITE_FORMS_API_BASE_URL=https://cms.example.com/
VITE_AUTH_TOKEN_URL=https://cms.example.com/api/episerver/connect/token
VITE_FORMS_CLIENT_ID=FRONTEND_CLIENT_ID
VITE_FORM_KEY=FORM_KEYVite exposes variables that start with VITE_ to the browser, so do not store secrets in this file.
- Replace the following values in .env:
- https://cms.example.com – The URL of your CMS site. End VITE_FORMS_API_BASE_URL with a slash, because the SDK appends _forms/v1/forms to it.
- FRONTEND_CLIENT_ID – The client ID of the OIDC application for the front end.
- FORM_KEY – The key of the form to display.
- Replace the contents of vite.config.ts with the following code:
import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, ".", "VITE_");
return {
plugins: [react()],
define: {
"process.env.REACT_APP_HEADLESS_FORM_BASE_URL": JSON.stringify(env.VITE_FORMS_API_BASE_URL),
},
};
});The Form component reads process.env.REACT_APP_HEADLESS_FORM_BASE_URL when a form redirects to a page after submission. Vite does not define process.env in the browser, so this configuration sets the variable to your CMS site URL.
Render the form
Add a router and the Form component to load the published form and let visitors submit it:
- Replace the contents of src/main.tsx with the following code. It wraps the app in a router so that the Form component can read the browser history:
import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);- Replace the contents of src/App.tsx with the following code. It renders the form and a sign-in form for visitors:
import { useState } from "react";
import { useHistory } from "react-router-dom";
import { Form, FormLogin } from "@episerver/forms-react";
import { FormCache, FormConstants, type IdentityInfo } from "@episerver/forms-sdk";
const formCache = new FormCache();
function App() {
const history = useHistory();
// FormLogin saves the access token in sessionStorage. Reuse it after a page reload.
const [identityInfo, setIdentityInfo] = useState<IdentityInfo>({
accessToken: formCache.get<string>(FormConstants.FormAccessToken),
} as IdentityInfo);
return (
<main>
<Form
formKey={import.meta.env.VITE_FORM_KEY}
language="en"
baseUrl={import.meta.env.VITE_FORMS_API_BASE_URL}
identityInfo={identityInfo}
history={history}
currentPageUrl={window.location.href}
/>
<FormLogin
clientId={import.meta.env.VITE_FORMS_CLIENT_ID}
authBaseUrl={import.meta.env.VITE_AUTH_TOKEN_URL}
onAuthenticated={setIdentityInfo}
/>
</main>
);
}
export default App;- Start the app:
npm run dev- On your CMS site, add the app's origin to AllowOrigins in the FormCorsPolicy option. Vite prints the origin when the app starts, such as http://localhost:5173. Keep AllowCredentials set to true, because the SDK loads forms with credentials.
- Add the same origin to the CMS site's CORS policy. FormCorsPolicy does not cover the token endpoint that FormLogin calls.
- Open the app in a browser. The form displays, and a visitor can sign in with FormLogin and submit it.
Before you deploy the CMS site to production, remove local origins from both CORS lists.
Load form keys from page content
The example displays one form with a fixed key. On a full site, a CMS page can contain several forms in a content area. Get the form keys from page content that your front end already loads, such as a Content Delivery API response. Render one Form component for each key.
Form and FormLogin properties
The Form component accepts the following properties:
- formKey – Required. The key of the form to display.
- baseUrl – Required. The base URL of the CMS site that hosts the Forms API. End the URL with a slash.
- language – The language code of the form, such as en.
- identityInfo – An object with the visitor's accessToken. The component sends the token when it submits the form.
- history – The object that useHistory() returns in React Router 5. The component uses it to go to another page, such as a form step that is attached to a page.
- currentPageUrl – The URL of the page that displays the form. The component uses it to find the current step of a multi-step form.
The FormLogin component accepts the following properties:
- clientId – Required. The client ID of the OIDC application.
- authBaseUrl – Required. The URL of the token endpoint.
- onAuthenticated – A function that receives an IdentityInfo object after the visitor signs in.
Note The submission endpoint requires an access token for every request. When a form allows anonymous submission, the Form component skips the sign-in check. The API still rejects a request without a token. Issue tokens for anonymous visitors from a token provider on your CMS site. For an example, see Setup Anonymous token provider with Headless Form.