Documentation
Feedback
Guides
App Development

App Development
Node apps
ClientsUsing Clients in Node apps
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 node Builder 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

  1. Start a new VTEX IO app using the node builder and open the project using your preferred code editor.

  2. Open the terminal and change to your app's node folder.

  3. Install the @vtex/api package by running the following command:


    _10
    yarn add @vtex/api

  4. In your app's handlers and middlewares, access the desired Clients via the ctx object. Here's an example of accessing the @vtex/api native licenseManager Client:


    _10
    export const authorize = async (ctx: Context) {
    _10
    const { clients: { licenseManager } } = ctx
    _10
    ...
    _10
    const 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.

  1. Start a new VTEX IO app using the node builder and open the project using your preferred code editor.

  2. Open the terminal and change to your app's node folder.

  3. Install the @vtex/api package by running the following command:


    _10
    yarn add @vtex/api

  4. Install the @vtex/clients package by running the following command:


    _10
    yarn add @vtex/clients

  5. Check the list of VTEX IO Clients available in the @vtex/clients package. Refer to List of native Clients and choose whether to use a Factory or an individual Client based on your requirements.

Using individual Clients
  1. Create a node/clients/index.ts file and import the desired Client.


    _10
    import { Catalog } from '@vtex/clients'

  2. In node/clients/index.ts, define a class called Clients that extends IOClients. This class is used to organize and configure your custom Clients. Within the Clients class, declare a get property 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 named catalog that uses the Catalog class.


    _10
    import { IOClients } from "@vtex/api";
    _10
    import { Catalog } from '@vtex/clients'
    _10
    _10
    export class Clients extends IOClients {
    _10
    public get catalog() {
    _10
    return this.getOrSet('catalog', Catalog)
    _10
    }
    _10
    }

  3. In your app's handlers and middlewares, access the desired Clients via the ctx object. Here's an example of accessing the catalog client and its getSkuById method:


    _10
    ctx.clients.catalog.getSkuById(...)

Using Client Factories
  1. Create a node/clients/index.ts file and import the desired factory. For example:


    _10
    import { masterDataFor } from '@vtex/clients'

  2. 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.

  3. In node/clients/index.ts, define a class called Clients that extends IOClients. This class is used to organize and configure your custom Clients. Within the Clients class, declare a get property 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 named books that uses the BooksClient class.


    _10
    import { IOClients } from "@vtex/api";
    _10
    const BooksClient = masterDataFor<MyBookType>('books')
    _10
    _10
    export class Clients extends IOClients {
    _10
    public get books() {
    _10
    return this.getOrSet('books', BooksClient)
    _10
    }
    _10
    }

  4. In your app's handlers and middlewares, access the desired Clients via the ctx object. Check the following example where we access the books client and its save method:


    _10
    ctx.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 StatusClient is set up in the service-example.

  1. After completing the steps in the Developing custom Clients guide, import the Clients class to the node/index.ts file.


    _10
    import { Clients } from "./clients";

  2. Create or edit the clients object of type ClientsConfig<Clients> from @vtex/api. This code sets up the configuration for Clients available in ctx.clients. It specifies an implementation property as Clients, which points to the custom Clients imported in the previous step, providing access to your custom Clients and their functionality.


    _11
    import type { ClientsConfig } from "@vtex/api";
    _11
    _11
    const clients: ClientsConfig<Clients> = {
    _11
    implementation: Clients,
    _11
    options: {
    _11
    default: {
    _11
    retries: 2,
    _11
    timeout: 2000,
    _11
    },
    _11
    },
    _11
    };

    Note that inside the options property, there's a default key 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.

  3. (Optional) In the node/index.ts file, consider adding a type declaration to improve type safety and code clarity. This declaration helps you define the Context type, which is based on ServiceContext<Clients, State>.


    _10
    import type { ServiceContext } from "@vtex/api";
    _10
    _10
    declare global {
    _10
    type Context = ServiceContext<Clients, State>;
    _10
    }

  4. In the node/index.ts file, export a new Service that defines route handlers and client options.


    _10
    export default new Service<Clients, State>({
    _10
    clients,
    _10
    routes: {
    _10
    ...
    _10
    },
    _10
    })

    For more information on how to set up routes, refer to the Routes guide.

  5. Now, in your app's handlers and middlewares, use the clients object from the ctx to access your custom Client. Check the following example where we access the custom github Client in the authorize function.


    _10
    export const authorize = async (ctx: Context) {
    _10
    const { clients: { github } } = ctx
    _10
    ...
    _10
    const data = await github.getUser(/*...*/)
    _10
    }

Options

The table below provides a detailed description of the available options for configuring your custom Client:

OptionDescription
authTypeSpecifies the authentication type.
timeoutSets the request timeout duration in milliseconds.
memoryCacheConfigures a memory cache layer for caching data.
diskCacheConfigures a disk cache layer for caching data.
baseURLDefines the base URL for making requests.
retriesSpecifies the number of times a request should be retried in case of failure.
exponentialTimeoutCoefficientConfigures the coefficient for exponential timeout backoff strategy.
initialBackoffDelaySets the initial delay before starting exponential backoff retries in milliseconds.
exponentialBackoffCoefficientConfigures the coefficient for exponential backoff retries.
metricsSpecifies an object for accumulating metrics related to requests.
concurrencyDefines the maximum number of concurrent requests.
headersSets default headers to be sent with every request.
paramsSets default query string parameters to be sent with every request.
middlewaresConfigures an array of middleware functions for request processing.
verboseEnables or disables verbose logging for requests and responses.
nameDefines a custom name for the instance.
serverTimingsSets server timings for measuring request and response times.
httpsAgentConfigures the HTTPS agent for making requests over SSL/TLS.
Contributors
1
Photo of the contributor
+ 1 contributors
Was this helpful?
Yes
No
Suggest Edits (GitHub)
Contributors
1
Photo of the contributor
+ 1 contributors
On this page