---
schema_version: "1"
id: 827ddb091921eb2b116cbfea90bf341ee001e510ecd3129eebe73421bde47ab0
title: Create a Salesforce Function
collection: developer
version: current
locale: en-us
portal_url: https://docs.salesforce.com/developer/current/en-us/salesforce-functions/functions/guide/quick-start/create-function.md
canonical_url: https://developer.salesforce.com/docs/platform/functions/guide/create-function.html
source_site: developer.salesforce.com
content_type: documentation
content_hash: 9f0f9f9955fdb928af8fb23db7114b57096778b5237f9321369377ec63adf6c0
products:
  - Salesforce Functions
---
# Create a Salesforce Function

**note:** This Quick Start provides code samples in Node.js with JavaScript. For examples using Java and TypeScript, see [Explore Solutions and Sample Code](https://developer.salesforce.com/docs/platform/functions/solutions_and_samples.md).

## Generate Your Function

You're ready to create your first function. Run this command in the project root directory:

```sh
sf generate function -n myfunction -l javascript
```

- `-n` the name of the function; must start with a letter and contain only lowercase letters and numbers
- `-l` the programming language for your function; `javascript`, `typescript`, or `java`

Your project now contains the basic scaffolding for your function, including supporting metadata and default boilerplate code. The project generation process creates a directory `myfunction` with default configuration files:

- A `package.json` file that contains information about dependencies.
- A `project.toml` file that contains function metadata information. See [Developer Guide: Function Metadata TOML Files](https://developer.salesforce.com/docs/platform/functions/dev-guide/toml.md) for more details.
- `index.js` that contains boilerplate code for your function. This file is your primary source code file. It's preconfigured with an entry point method that has parameters used to pass payload data to the function and to communicate with the invoking org. The default function in `index.js` logs the received payload, issues a query for Account data, and logs the query results.

```javascript
export default async function (event, context, logger) {
  logger.info(`Invoking myfunction with payload ${JSON.stringify(event.data || {})}`);

  const results = await context.org.data.query("SELECT Id, Name FROM Account");
  logger.info(JSON.stringify(results));
  return results;
}
```

The function parameters are:

| Parameter | Description                                                                                                                                                                  |
| --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| event     | An Event object that describes the triggering event and contains event data. This parameter also contains event data in the `data` property, sometimes called the `payload`. |
| context   | Salesforce org context for reading from and writing to Salesforce. The context is pre-configured to be authenticated to the invoking org.                                    |
| logger    | Salesforce logger for the function.                                                                                                                                          |

## Finish Writing Your Function

Edit `index.js` and update your function to match the following example. This function uses the [Salesforce Functions SDK for Node.js](https://developer.salesforce.com/docs/platform/functions/nodesdk/NODE_README.md) to insert a new Account record in your scratch org. It then queries all Account records with the given fields in the org. The new Account's name is populated from the `name` field of the payload.

```javascript
export default async function (event, context, logger) {
  logger.info(`Invoking salesforcesdkjs function with payload ${JSON.stringify(event.data || {})}`);

  // Extract properties from payload
  const { name, accountNumber, industry, type, website } = event.data;

  // Validate the payload params
  if (!name) {
    throw new Error(`Please provide account name`);
  }

  // Define a record using the RecordForCreate type and providing the Developer Name
  const account = {
    type: "Account",
    fields: {
      Name: `${name}-${Date.now()}`,
      AccountNumber: accountNumber,
      Industry: industry,
      Type: type,
      Website: website,
    },
  };

  try {
    // Insert the record using the SalesforceSDK DataApi and get the new Record Id from the result
    const { id: recordId } = await context.org.dataApi.create(account);

    // Query Accounts using the SalesforceSDK DataApi to verify that your new Account was created.
    const soql = `SELECT Fields(STANDARD) FROM Account WHERE Id = '${recordId}'`;
    const queryResults = await context.org.dataApi.query(soql);
    return queryResults;
  } catch (err) {
    // Catch any DML errors and pass the throw an error with the message
    const errorMessage = `Failed to insert record. Root Cause: ${err.message}`;
    logger.error(errorMessage);
    throw new Error(errorMessage);
  }
}
```

**tip:** This code is from [Context_SalesforceSDK_JS sample](https://github.com/trailheadapps/functions-recipes/tree/main/functions/03_Context_SalesforceSDK_JS) in the [functions-recipes GitHub repo](https://github.com/trailheadapps/functions-recipes/).
