Skip to main content
The createRecord method from lightning/uiRecordApi allows you to create records programmatically without writing server-side Apex code. It leverages Lightning Data Service for caching and offline support.

Import

import { createRecord } from 'lightning/uiRecordApi';

Usage

import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { createRecord } from 'lightning/uiRecordApi';
import { reduceErrors } from 'c/ldsUtils';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';

export default class LdsCreateRecord extends LightningElement {
    accountId;
    name = '';

    handleNameChange(event) {
        this.accountId = undefined;
        this.name = event.target.value;
    }

    async createAccount() {
        const fields = {};
        fields[NAME_FIELD.fieldApiName] = this.name;
        const recordInput = { apiName: ACCOUNT_OBJECT.objectApiName, fields };
        try {
            const account = await createRecord(recordInput);
            this.accountId = account.id;
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: 'Account created',
                    variant: 'success'
                })
            );
        } catch (error) {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error creating record',
                    message: reduceErrors(error).join(', '),
                    variant: 'error'
                })
            );
        }
    }
}
<template>
    <lightning-input
        label="Id"
        disabled
        value={accountId}
    ></lightning-input>
    <lightning-input
        label="Name"
        onchange={handleNameChange}
    ></lightning-input>
    <lightning-button
        label="Create Account"
        variant="brand"
        onclick={createAccount}
    ></lightning-button>
</template>

Syntax

createRecord(recordInput)

Parameters

recordInput (Object) An object with the following properties:
PropertyTypeRequiredDescription
apiNameStringYesAPI name of the object (e.g., ‘Account’, ‘Contact’)
fieldsObjectYesObject mapping field API names to values
recordTypeIdStringNoRecord type ID for the new record

Return Value

Returns a Promise that resolves to an object containing:
  • id - The ID of the newly created record
  • fields - The field values of the created record
  • apiName - The object API name

Example: Creating with Multiple Fields

import NAME_FIELD from '@salesforce/schema/Contact.Name';
import EMAIL_FIELD from '@salesforce/schema/Contact.Email';
import PHONE_FIELD from '@salesforce/schema/Contact.Phone';
import CONTACT_OBJECT from '@salesforce/schema/Contact';

async createContact() {
    const fields = {};
    fields[NAME_FIELD.fieldApiName] = 'John Doe';
    fields[EMAIL_FIELD.fieldApiName] = '[email protected]';
    fields[PHONE_FIELD.fieldApiName] = '555-0100';
    
    const recordInput = {
        apiName: CONTACT_OBJECT.objectApiName,
        fields
    };
    
    try {
        const contact = await createRecord(recordInput);
        console.log('Contact created with ID:', contact.id);
    } catch (error) {
        console.error('Error creating contact:', error);
    }
}

Error Handling

Use the reduceErrors utility to format error messages:
import { reduceErrors } from 'c/ldsUtils';

try {
    await createRecord(recordInput);
} catch (error) {
    const errorMessages = reduceErrors(error);
    // errorMessages is an array of user-friendly error strings
    console.error(errorMessages.join(', '));
}

LDS Utility: reduceErrors

The reduceErrors utility function extracts user-friendly error messages from Lightning Data Service errors:
/**
 * Reduces one or more LDS errors into a string[] of error messages.
 * @param {Object|Object[]} errors - Error object or array of error objects
 * @returns {String[]} Array of error messages
 */
export function reduceErrors(errors) {
    if (!Array.isArray(errors)) {
        errors = [errors];
    }

    return (
        errors
            .filter((error) => !!error)
            .map((error) => {
                if (Array.isArray(error.body)) {
                    return error.body.map((e) => e.message);
                } else if (error.body && typeof error.body.message === 'string') {
                    return error.body.message;
                } else if (typeof error.message === 'string') {
                    return error.message;
                }
                return 'Unknown error';
            })
            .reduce((prev, curr) => prev.concat(curr), [])
            .filter((message) => !!message)
    );
}

Features

  • No Apex Required: Create records without writing server-side code
  • Lightning Data Service: Automatic caching and offline support
  • Type Safety: Use schema imports for field API names
  • Validation: Automatic field and object validation
  • Security: Respects field-level and object-level security
Always consider using lightning-record-form or lightning-record-edit-form first. Use createRecord only when you need programmatic control over record creation, such as creating records in response to complex business logic or user interactions.
The createRecord method respects object and field-level security. Users must have create permission on the object and edit permission on all specified fields.

Build docs developers (and LLMs) love