Using Node Clients
Learn how to use Clients in your VTEX IO app for interaction with both internal and external services.
In VTEX IO Services, Node Clients are powerful tools that enable you to seamlessly interact with both internal and external services. These clients play a crucial role in tasks such as making API requests, fetching data, and performing various operations within your VTEX IO apps. This guide will walk you through the effective utilization of Node Clients.
For this guide, note that VTEX IO Services exports functions that receive a context object. These functions can be resolver functions for GraphQL fields, middlewares for an HTTP server, or event handlers. In all cases, the Service receives a ctx object of type Context, and it is within ctx.clients where you will find your Clients.
Before you begin
Before diving into using Clients within your VTEX IO app, ensure you have the following prerequisites in place:
- VTEX IO development workspace: Ensure you have a VTEX IO development workspace set up. For more information, refer to Creating a Development workspace.
- TypeScript Familiarity: This guide assumes you have a basic understanding of TypeScript, as we'll be using the
nodeBuilder to develop with TypeScript. For more information, refer to Typescript's official documentation. - Understanding of Clients: Clients play a crucial role in facilitating interactions between your application and both external and internal services. For more information, refer to Clients.
Using native @vtex/api Clients
-
Start a new VTEX IO app using the
nodebuilder and open the project using your preferred code editor. -
Open the terminal and change to your app's
nodefolder. -
Install the
@vtex/apipackage by running the following command:_10yarn add @vtex/api -
In your app's handlers and middlewares, access the desired Clients via the
ctxobject. Here's an example of accessing the@vtex/apinativelicenseManagerClient:_10export const authorize = async (ctx: Context) {_10const { clients: { licenseManager } } = ctx_10..._10const data = await licenseManager.canAccessResource(/*...*/)_10}
Using native @vtex/clients Clients
The @vtex/clients package exports Clients, Client Factories and TypeScript typings that help you connect a VTEX IO app with VTEX Core Commerce modules.
-
Start a new VTEX IO app using the
nodebuilder and open the project using your preferred code editor. -
Open the terminal and change to your app's
nodefolder. -
Install the
@vtex/apipackage by running the following command:_10yarn add @vtex/api -
Install the
@vtex/clientspackage by running the following command:_10yarn add @vtex/clients -
Check the list of VTEX IO Clients available in the
@vtex/clientspackage. Refer to List of native Clients and choose whether to use a Factory or an individual Client based on your requirements.
Using individual Clients
-
Create a
node/clients/index.tsfile and import the desired Client._10import { Catalog } from '@vtex/clients' -
In
node/clients/index.ts, define a class calledClientsthat extendsIOClients. This class is used to organize and configure your custom Clients. Within the Clients class, declare agetproperty for each of your custom Clients. This property allows you to access a specific Client by name. In our example, we've created a client namedcatalogthat uses theCatalogclass._10import { IOClients } from "@vtex/api";_10import { Catalog } from '@vtex/clients'_10_10export class Clients extends IOClients {_10public get catalog() {_10return this.getOrSet('catalog', Catalog)_10}_10} -
In your app's handlers and middlewares, access the desired Clients via the
ctxobject. Here's an example of accessing thecatalogclient and itsgetSkuByIdmethod:_10ctx.clients.catalog.getSkuById(...)
Using Client Factories
-
Create a
node/clients/index.tsfile and import the desired factory. For example:_10import { masterDataFor } from '@vtex/clients' -
Follow the instructions for each factory, using its methods to create a Client class. Refer to Creating a Master Data CRUD app for more information on how to use the Master Data factory.
-
In
node/clients/index.ts, define a class calledClientsthat extendsIOClients. This class is used to organize and configure your custom Clients. Within the Clients class, declare agetproperty for each of your custom Clients. This property allows you to access a specific Client by name. In our example, we've created a client namedbooksthat uses theBooksClientclass._10import { IOClients } from "@vtex/api";_10const BooksClient = masterDataFor<MyBookType>('books')_10_10export class Clients extends IOClients {_10public get books() {_10return this.getOrSet('books', BooksClient)_10}_10} -
In your app's handlers and middlewares, access the desired Clients via the
ctxobject. Check the following example where we access thebooksclient and itssavemethod:_10ctx.clients.books.save({ name: 'Example Book' })
Using custom Clients
If you have developed custom Clients for a specific need, take the following steps to use them in your VTEX IO app.
For a practical example, you can refer to how the
StatusClientis set up in theservice-example.
-
After completing the steps in the Developing custom Clients guide, import the
Clientsclass to thenode/index.tsfile._10import { Clients } from "./clients"; -
Create or edit the
clientsobject of typeClientsConfig<Clients>from@vtex/api. This code sets up the configuration for Clients available inctx.clients. It specifies animplementationproperty asClients, which points to the custom Clients imported in the previous step, providing access to your custom Clients and their functionality._11import type { ClientsConfig } from "@vtex/api";_11_11const clients: ClientsConfig<Clients> = {_11implementation: Clients,_11options: {_11default: {_11retries: 2,_11timeout: 2000,_11},_11},_11};Note that inside the
optionsproperty, there's adefaultkey with default Client options. These options include specifying the number of retries and the timeout for HTTP requests. See the Options table for more options. All IO Clients will be initialized with these options unless otherwise specified. -
(Optional) In the
node/index.tsfile, consider adding a type declaration to improve type safety and code clarity. This declaration helps you define theContexttype, which is based onServiceContext<Clients, State>._10import type { ServiceContext } from "@vtex/api";_10_10declare global {_10type Context = ServiceContext<Clients, State>;_10} -
In the
node/index.tsfile, export a new Service that defines route handlers and client options._10export default new Service<Clients, State>({_10clients,_10routes: {_10..._10},_10})For more information on how to set up routes, refer to the Routes guide.
-
Now, in your app's handlers and middlewares, use the
clientsobject from thectxto access your custom Client. Check the following example where we access the customgithubClient in theauthorizefunction._10export const authorize = async (ctx: Context) {_10const { clients: { github } } = ctx_10..._10const data = await github.getUser(/*...*/)_10}
Options
The table below provides a detailed description of the available options for configuring your custom Client:
| Option | Description |
|---|---|
authType | Specifies the authentication type. |
timeout | Sets the request timeout duration in milliseconds. |
memoryCache | Configures a memory cache layer for caching data. |
diskCache | Configures a disk cache layer for caching data. |
baseURL | Defines the base URL for making requests. |
retries | Specifies the number of times a request should be retried in case of failure. |
exponentialTimeoutCoefficient | Configures the coefficient for exponential timeout backoff strategy. |
initialBackoffDelay | Sets the initial delay before starting exponential backoff retries in milliseconds. |
exponentialBackoffCoefficient | Configures the coefficient for exponential backoff retries. |
metrics | Specifies an object for accumulating metrics related to requests. |
concurrency | Defines the maximum number of concurrent requests. |
headers | Sets default headers to be sent with every request. |
params | Sets default query string parameters to be sent with every request. |
middlewares | Configures an array of middleware functions for request processing. |
verbose | Enables or disables verbose logging for requests and responses. |
name | Defines a custom name for the instance. |
serverTimings | Sets server timings for measuring request and response times. |
httpsAgent | Configures the HTTPS agent for making requests over SSL/TLS. |