Learn about the Square Node.js SDK features.
There are two different ways you can make the Square Node.js SDK available to your application:
CommonJS style - Use the
const
statement, as shown in the following example:const { Client, Environment, ApiError } = require('square')ES module style - Use the
import
statement, as shown in the following example:import { Client, Environment, ApiError } from "square";Important
Don't mix CommonJS and ES imports in the same codebase. Instead, choose one style and use it consistently. Otherwise, you're likely to encounter issues that are hard to debug. For more information, see Dual package hazard in the Node.js documentation.
To use the SDK, instantiate a Client
object and initialize it with the appropriate environment and corresponding access token, as shown:
For testing, Square provides a Sandbox environment as shown in the following code fragment:
const client = new Client({ bearerAuthCredentials: { accessToken: process.env.SQUARE_ACCESS_TOKEN }, environment: Environment.Sandbox });To access production resources, set the environment to
Environment.Production
as shown:const client = new Client({ bearerAuthCredentials: { accessToken: process.env.SQUARE_ACCESS_TOKEN }, environment: Environment.Production, });To set a custom environment, provide a
customUrl
and set the environment tocustom
, as shown:const client = new Client({ bearerAuthCredentials: { accessToken: process.env.SQUARE_ACCESS_TOKEN }, environment: Environment.Custom, customUrl: "https://your.customdomain.com", });
After you create a client, don't attempt to modify it. Instead, create a new client instance (based on an existing client) using the withConfiguration
method.
For example, suppose that you already created a Client
object (named myOldClient
), but want to use a different access token. You can create a new client that has the same configuration state as myOldClient
and override the new client's accessToken
attribute, as shown:
const myNewClient = myOldClient.withConfiguration({
bearerAuthCredentials: {
accessToken: process.env.SQUARE_ACCESS_TOKEN
},
});
This example assumes that you defined the OTHER_ACCESS_TOKEN
environment variable prior to running the code.
When you have a Client
object, you need to create an instance of the Square API that you want to use. For example:
const { locationsApi } = client;
If you want to work with multiple Square APIs, you can create an instance of each. For example:
const { locationsApi, customersApi, ordersApi } = client;
The following example shows how to call a Square API:
const { Client, Environment, ApiError } = require ("square");
const client = new Client({
bearerAuthCredentials: {
accessToken: process.env.SQUARE_ACCESS_TOKEN
},
environment: Environment.Sandbox,
});
const { locationsApi } = client;
async function getLocations() {
try {
let listLocationsResponse = await locationsApi.listLocations();
let locations = listLocationsResponse.result.locations;
locations.forEach(function (location) {
console.log(
location.id + ": " +
location.name +", " +
location.address.addressLine1 + ", " +
location.address.locality
);
});
} catch (error) {
if (error instanceof ApiError) {
error.result.errors.forEach(function (e) {
console.log(e.category);
console.log(e.code);
console.log(e.detail);
});
} else {
console.log("Unexpected error occurred: ", error);
}
}
};
getLocations()
The Client
object instantiates every API class and exposes them as properties. You work with an API by calling methods on an instance of an API class. Most of these methods require you to provide a JSON object that contains the request body.
Some API classes accept nested data (for example, address
, customer
, and order
). For these, you can embed other JSON objects within the request body.
The following code creates a new customer, with a nested object for address
. The idempotencyKey
parameter ensures that the new customer is only created once, even if you run the code multiple times.
const { Client, Environment, ApiError } = require("square");
const { randomUUID } = require("crypto");
const client = new Client({
bearerAuthCredentials: {
accessToken: process.env.SQUARE_ACCESS_TOKEN
},
environment: Environment.Sandbox,
});
const { customersApi } = client;
async function createCustomer() {
try {
let createCustomerResponse = await customersApi.createCustomer({
givenName: "John",
familyName: "Doe",
address: {
addressLine1: "1455 Market St",
addressLine2: "San Francisco, CA 94103",
},
idempotencyKey: randomUUID(),
});
const customer = createCustomerResponse.result.customer;
console.log(
"New customer created with customer ID " +
customer.id
);
} catch (error) {
if (error instanceof ApiError) {
error.result.errors.forEach(function (e) {
console.log(e.category);
console.log(e.code);
console.log(e.detail);
});
} else {
console.log("Unexpected error occurred: ", error);
}
}
};
createCustomer();
The Square API endpoints can have path parameters, query parameters, and a request body. When you make corresponding method calls using the Square Node.js SDK, you provide the values as follows:
Request body - In the Square Node.js SDK, a request body is represented by a JSON object. Depending on the method being called, the parameter values are represented as JSON values, arrays, or embedded objects.
const { Client, Environment, ApiError } = require("square"); const { randomUUID } = require("crypto"); const client = new Client({ bearerAuthCredentials: { accessToken: process.env.SQUARE_ACCESS_TOKEN }, environment: Environment.Sandbox, }); const { customersApi } = client; async function createCustomer() { try { let createCustomerResponse = await customersApi.createCustomer({ givenName: "Mary", familyName: "Smith", address: { addressLine1: "1455 Market St", addressLine2: "San Francisco, CA 94103", }, idempotencyKey: randomUUID(), }); const customer = createCustomerResponse.result.customer; console.log(customer); } catch (error) { if (error instanceof ApiError) { error.result.errors.forEach(function (e) { console.log(e.category); console.log(e.code); console.log(e.detail); }); } else { console.log("Unexpected error occurred: ", error); } } }; createCustomer();Path and query parameters - For example:
- The RetrieveCustomer endpoint has a
customer_id
path parameter (GET /v2/customers/{customer_id}
). - The ListCustomers endpoint has several query parameters such as
cursor
andlimit
.
You provide these as parameters to the method calls. The following example passes the
customer_id
path parameter as a parameter to theupdateCustomer
method:async function updateCustomer() { try { let customerId = "GZ48C4P2CWVXV7F7K2ZH795RSG"; let body = { givenName: "Fred", familyName: "Jones", address: { addressLine1: "1455 Market St", addressLine2: "San Francisco, CA 94103", }, version: 0, }; let updateCustomerResponse = await customersApi.updateCustomer( customerId, body ); console.log(updateCustomerResponse.result); } catch (error) { if (error instanceof ApiError) { error.result.errors.forEach(function (e) { console.log(e.category); console.log(e.code); console.log(e.detail); }); } else { console.log("Unexpected error occurred: ", error); } } };For an example of query parameters, see Pagination.
- The RetrieveCustomer endpoint has a
You can configure the number of retries and the timeout values for HTTP requests when using the Square Node.js SDK:
Retries - By default, the Square SDK doesn't retry a failed request. When your application starts, the Square SDK sets the number of retries to 0. You have the option to configure a different value when you create a client. Retries can help improve application stability by allowing applications to handle momentary failures in connecting to a service by transparently retrying a failed request.
Timeout - Timeout is the time period that a client waits for a server response. The Square SDK sets the default timeout to 60 seconds. On timeout, the SDK throws an exception. You have the option to configure a timeout value at the client level.
The following code creates a client, setting the number of retries to 2 and the timeout to 10 seconds (10,000 milliseconds):
const client = new Client({
bearerAuthCredentials: {
accessToken: process.env.SQUARE_ACCESS_TOKEN
},
environment: Environment.Sandbox,
httpClientOptions: {
timeout: 10000,
retryConfig: {
maxNumberOfRetries: 2,
maximumRetryWaitTime: 1000000,
}
});
Use maximumRetryWaitTime
to define a cumulative upper limit for all retry activity during the request. If the total amount of time spent (in milliseconds) exceeds maximumRetryWaitTime
, the request times out even if there are retries still remaining.
The default value for maximumRetryWaitTime
is 0, which effectively disables retries for the request. You should set maximumRetryWaitTime
to the maximum number of milliseconds that you want to wait.
If an API call succeeds, it returns an ApiResponse
object that contains the data returned from the call.
If an API call fails, it throws an ApiError
. This occurs when the status code of a response is outside of the HTTP 2xx range (not successful).
Both ApiResponse
and ApiError
contain additional properties describing the low-level details of the request and response.
When working with the Square Node.js SDK and processing the ApiResponse
, you receive both the body
and result
of the response. You should always process and read from the response’s result
instead of the body
. The body
is the raw JSON data returned from the API, but the result
structure matches the types defined in the SDK and API Reference documentation.
async function listLocations() {
try {
let listLocationsResponse = await locationsApi.listLocations();
let locations = listLocationsResponse.result.locations;
print("Successfully called List Locations");
// Your business logic here
} catch (error) {
// Your error-handling code here
if (error instanceof ApiError) {
error.result.errors.forEach(function (e) {
console.log(e.category);
console.log(e.code);
console.log(e.detail);
});
} else {
console.log("Unexpected error occurred: ", error);
}
}
};
For more information, see Square API errors.