🔄 Continuation: Saving Sitecore XM Cloud Form Data to SQL Database

 This blog is a continuation of my previous post: Customizing XM Cloud Form Component. In this article, I will walk you through how to save Sitecore XM Cloud form submissions to a SQL Server database using the XM Cloud Starter Kit.


🛠️ Sitecore CMS Changes

1. Create an XM Cloud Form

I assume you already know how to create forms in XM Cloud. If not, please check the official Sitecore documentation.

2. Duplicate and Customize the Form Component

Duplicate the existing form component from the XM Cloud Starter Kit and customize it as needed. I covered this process in detail in my previous blog post:
👉 Customizing XM Cloud Form Component


🧱 XM Cloud Starter Kit Code Changes

Step 1: Install MSSQL Package

In your Next.js starter kit, install the mssql package:

npm install mssql

Step 2: Create a Webhook

Navigate to the following directory in your project:

/headapps/nextjs-starter/src/pages/api/

Create a webhook, file named saveformdata.ts (or submit-form.ts). Paste the following code into that file:

// pages/api/saveformdata.ts import type { NextApiRequest, NextApiResponse } from 'next'; import sql from 'mssql'; // SQL Server connection config — update with your local setup const config = { user: 'sitecore', password: 'sitecore', server: 'YOUR_SQL_SERVER_NAME', database: 'CustomFormDB', options: { instanceName: 'SQLEXPRESS', encrypt: false, trustServerCertificate: true, }, }; export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method !== 'POST') { return res.status(405).json({ error: 'Method not allowed' }); } try { const data = req.body; // Destructure fields from form const name = data.text_cf4be; const email = data.email_1c499; const phoneRaw = data.phone_8a15d; const formId = data.formid; console.log('FormId:', formId); const phoneNumber = Number(phoneRaw); // Connect to SQL Server await sql.connect(config); // Use a parameterized query to prevent SQL injection const result = await sql.query` INSERT INTO customtable (Name, Email, phone, formId) VALUES (${name}, ${email}, ${phoneNumber}, ${formId}) `; console.log('SQL Insert Result:', result); return res.status(200).json({ message: 'Form data saved successfully', data }); } catch (error) { console.error('Error saving form data:', error); return res.status(500).json({ error: 'Internal server error' }); } }

🔍 Code Explanation

🔐 SQL Server Configuration

Update this section of the code with your local SQL Server details:

const config = { user: 'sitecore', password: 'sitecore', server: 'YOUR_SERVER_NAME', database: 'CustomFormDB', options: { instanceName: 'SQLEXPRESS', encrypt: false, trustServerCertificate: true, }, };

⚠️ Make sure encrypt and trustServerCertificate values match your environment setup.


🧩 Form Data Destructuring

This part of the code extracts data from the form submission:

const name = data.text_cf4be; const email = data.email_1c499; const phoneRaw = data.phone_8a15d; const formId = data.formid;

Make sure the keys (like text_cf4be, email_1c499) match the field IDs from your custom form.


💾 Inserting Data into SQL Server

Here’s where the form data is saved using a parameterized query:

const result = await sql.query` INSERT INTO customtable (Name, Email, phone, formId) VALUES (${name}, ${email}, ${phoneNumber}, ${formId}) `;

This helps prevent SQL injection and safely stores the data.


🐞 Common Issue & Fix

After setting everything up, you might run into this error:

"SQL Server connection timeout / not reachable"

 

✅ Fix:

You need to start the SQL Server Browser service manually:

  1. Go to Windows Services (services.msc)

  2. Locate SQL Server Browser

  3. Right-click → Start

Once started, retry submitting the form.


✅ Final Verification

Step 1: Submit the Form

Go to your form page and fill in the form details.

                

Step 2: Check SQL Server

Open SQL Server Management Studio (SSMS) and run:

SELECT * FROM customtable;

You should see your form data saved successfully 🎉


📌 Conclusion

That’s it! You’ve now connected your Sitecore XM Cloud form to a SQL Server database using the XM Cloud Starter Kit and a simple API webhook.

If you haven't customized your form yet, make sure to follow the steps in my previous blog post here:
👉 Customizing XM Cloud Form Component

Comments

Popular posts from this blog

Solrcloud With Zookeeper -Single server setup

Render Sitecore Experience Forms Using Sitecore XP 10.4 with a Headless Approach (Next.js + JSS SDK)

Next.js with XM Cloud EDGE and GraphQL