Skip to content
SwapKit is a powerful suite of tools for building blockchain applications.

Vite

This guide will help you integrate SwapKit into your Vite application with proper Node.js polyfills and WebAssembly support.

Install SwapKit and required dependencies:

bun add @swapkit/sdk vite-plugin-node-polyfills

Update your vite.config.ts to include necessary polyfills and WebAssembly support:

import { function defineConfig(config: UserConfig): UserConfig (+5 overloads)
Type helper to make it easier to use vite.config.ts accepts a direct {@link UserConfig } object, or a function that returns it. The function receives a {@link ConfigEnv } object.
defineConfig
} from 'vite';
import function react(opts?: Options): PluginOption[]react from '@vitejs/plugin-react'; import function wasm(): anywasm from "vite-plugin-wasm"; import function topLevelAwait(options?: Options): PlugintopLevelAwait from "vite-plugin-top-level-await"; import { const nodePolyfills: (options?: PolyfillOptions) => Plugin
Returns a Vite plugin to polyfill Node's Core Modules for browser environments. Supports `node:` protocol imports.
@example```ts // vite.config.ts import { defineConfig } from 'vite' import { nodePolyfills } from 'vite-plugin-node-polyfills' export default defineConfig({ plugins: [ nodePolyfills({ // Specific modules that should not be polyfilled. exclude: [], // Whether to polyfill specific globals. globals: { Buffer: true, // can also be 'build', 'dev', or false global: true, process: true, }, // Whether to polyfill `node:` protocol imports. protocolImports: true, }), ], }) ```
nodePolyfills
} from 'vite-plugin-node-polyfills';
export default function defineConfig(config: UserConfig): UserConfig (+5 overloads)
Type helper to make it easier to use vite.config.ts accepts a direct {@link UserConfig } object, or a function that returns it. The function receives a {@link ConfigEnv } object.
defineConfig
({
UserConfig.plugins?: PluginOption[] | undefined
Array of vite plugins to use.
plugins
: [
function react(opts?: Options): PluginOption[]react(), function wasm(): anywasm(), function topLevelAwait(options?: Options): PlugintopLevelAwait(), function nodePolyfills(options?: PolyfillOptions): Plugin
Returns a Vite plugin to polyfill Node's Core Modules for browser environments. Supports `node:` protocol imports.
@example```ts // vite.config.ts import { defineConfig } from 'vite' import { nodePolyfills } from 'vite-plugin-node-polyfills' export default defineConfig({ plugins: [ nodePolyfills({ // Specific modules that should not be polyfilled. exclude: [], // Whether to polyfill specific globals. globals: { Buffer: true, // can also be 'build', 'dev', or false global: true, process: true, }, // Whether to polyfill `node:` protocol imports. protocolImports: true, }), ], }) ```
nodePolyfills
({
exclude: ['fs'],
globals?: {
    Buffer?: BooleanOrBuildTarget;
    global?: BooleanOrBuildTarget;
    process?: BooleanOrBuildTarget;
} | undefined
Specify whether specific globals should be polyfilled.
@example```ts nodePolyfills({ globals: { Buffer: false, global: true, process: 'build', }, }) ```
globals
: {
Buffer?: BooleanOrBuildTarget | undefinedBuffer: true, global?: BooleanOrBuildTarget | undefinedglobal: true, process?: BooleanOrBuildTarget | undefinedprocess: true, }, protocolImports?: boolean | undefined
Specify whether the Node protocol version of an import (e.g. `node:buffer`) should be polyfilled too.
@defaulttrue
protocolImports
: true,
}), ], define?: Record<string, any> | undefined
Define global variable replacements. Entries will be defined on `window` during dev and replaced during build.
define
: {
'process.env': {}, global: stringglobal: 'globalThis', }, UserConfig.optimizeDeps?: DepOptimizationOptions | undefined
Dep optimization options
optimizeDeps
: {
DepOptimizationConfig.esbuildOptions?: Omit<BuildOptions, "bundle" | "entryPoints" | "external" | "write" | "watch" | "outdir" | "outfile" | "outbase" | "outExtension" | "metafile"> | undefined
Options to pass to esbuild during the dep scanning and optimization Certain options are omitted since changing them would not be compatible with Vite's dep optimization. - `external` is also omitted, use Vite's `optimizeDeps.exclude` option - `plugins` are merged with Vite's dep plugin https://esbuild.github.io/api
esbuildOptions
: {
target?: string | string[] | undefined
Documentation: https://esbuild.github.io/api/#target
target
: 'esnext',
}, }, build?: BuildEnvironmentOptions | undefined
Build specific options
build
: {
BuildEnvironmentOptions.target?: string | false | string[] | undefined
Compatibility transform target. The transform is performed with esbuild and the lowest supported target is es2015. Note this only handles syntax transformation and does not cover polyfills Default: 'modules' - transpile targeting browsers that natively support dynamic es module imports and `import.meta` (Chrome 87+, Firefox 78+, Safari 14+, Edge 88+). Another special value is 'esnext' - which only performs minimal transpiling (for minification compat). For custom targets, see https://esbuild.github.io/api/#target and https://esbuild.github.io/content-types/#javascript for more details.
@default'modules'
target
: 'esnext',
}, });

Create a SwapKit client instance:

// src/swapKitClient.ts
import { 
function createSwapKit(config?: Parameters<typeof SwapKit>[0]): {
    chainflip: {
        supportedSwapkitProviders: ProviderName[];
    } & {
        swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
    };
    ... 5 more ...;
    near: {
        ...;
    } & {
        ...;
    };
} & {
    ...;
} & {
    ...;
}
createSwapKit
} from '@swapkit/sdk';
export const
const swapKitClient: {
    chainflip: {
        supportedSwapkitProviders: ProviderName[];
    } & {
        swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
    };
    ... 5 more ...;
    near: {
        ...;
    } & {
        ...;
    };
} & {
    ...;
} & {
    ...;
}
swapKitClient
=
function createSwapKit(config?: Parameters<typeof SwapKit>[0]): {
    chainflip: {
        supportedSwapkitProviders: ProviderName[];
    } & {
        swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
    };
    ... 5 more ...;
    near: {
        ...;
    } & {
        ...;
    };
} & {
    ...;
} & {
    ...;
}
createSwapKit
();

Here’s a basic example of using SwapKit in a React component:

// src/App.tsx
import { function useState<S>(initialState: S | (() => S)): [S, React.Dispatch<React.SetStateAction<S>>] (+1 overload)
Returns a stateful value, and a function to update it.
@version16.8.0@see{@link https://react.dev/reference/react/useState}
useState
, function useEffect(effect: React.EffectCallback, deps?: React.DependencyList): void
Accepts a function that contains imperative, possibly effectful code.
@parameffect Imperative function that can return a cleanup function@paramdeps If present, effect will only activate if the values in the list change.@version16.8.0@see{@link https://react.dev/reference/react/useEffect}
useEffect
} from 'react';
import { import swapKitClientswapKitClient } from
Cannot find module './swapKitClient' or its corresponding type declarations.
'./swapKitClient'
;
import { enum ChainChain, enum WalletOptionWalletOption } from '@swapkit/sdk'; function function App(): React.JSX.ElementApp() { const [const isConnected: booleanisConnected, const setIsConnected: React.Dispatch<React.SetStateAction<boolean>>setIsConnected] = useState<boolean>(initialState: boolean | (() => boolean)): [boolean, React.Dispatch<React.SetStateAction<boolean>>] (+1 overload)
Returns a stateful value, and a function to update it.
@version16.8.0@see{@link https://react.dev/reference/react/useState}
useState
(false);
const [const address: stringaddress, const setAddress: React.Dispatch<React.SetStateAction<string>>setAddress] = useState<string>(initialState: string | (() => string)): [string, React.Dispatch<React.SetStateAction<string>>] (+1 overload)
Returns a stateful value, and a function to update it.
@version16.8.0@see{@link https://react.dev/reference/react/useState}
useState
<string>('');
const const connectWallet: () => Promise<void>connectWallet = async () => { try { await import swapKitClientswapKitClient.connectEVMWallet([enum ChainChain.function (enum member) Chain.Ethereum = "ETH"Ethereum], enum WalletOptionWalletOption.function (enum member) WalletOption.METAMASK = "METAMASK"METAMASK); const setIsConnected: (value: React.SetStateAction<boolean>) => voidsetIsConnected(true); const const ethAddress: anyethAddress = await import swapKitClientswapKitClient.getAddress(enum ChainChain.function (enum member) Chain.Ethereum = "ETH"Ethereum); const setAddress: (value: React.SetStateAction<string>) => voidsetAddress(const ethAddress: anyethAddress); } catch (error) { console.Console.error(message?: any, ...optionalParams: any[]): void (+3 overloads)
Prints to `stderr` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). ```js const code = 5; console.error('error #%d', code); // Prints: error #5, to stderr console.error('error', code); // Prints: error 5, to stderr ``` If formatting elements (e.g. `%d`) are not found in the first string then [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options) is called on each argument and the resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
error
('Failed to connect wallet:', error);
} }; const const disconnectWallet: () => voiddisconnectWallet = () => { import swapKitClientswapKitClient.disconnectWallet(enum ChainChain.function (enum member) Chain.Ethereum = "ETH"Ethereum); const setIsConnected: (value: React.SetStateAction<boolean>) => voidsetIsConnected(false); const setAddress: (value: React.SetStateAction<string>) => voidsetAddress(''); }; return ( <
'React' refers to a UMD global, but the current file is a module. Consider adding an import instead.
div
>
<
'React' refers to a UMD global, but the current file is a module. Consider adding an import instead.
h1
>SwapKit + Vite</h1>
{!const isConnected: booleanisConnected ? ( <
'React' refers to a UMD global, but the current file is a module. Consider adding an import instead.
button
onClick={const connectWallet: () => Promise<void>connectWallet}>Connect Wallet</button>
) : ( <
'React' refers to a UMD global, but the current file is a module. Consider adding an import instead.
div
>
<
'React' refers to a UMD global, but the current file is a module. Consider adding an import instead.
p
>Connected: {const address: stringaddress}</p>
<
'React' refers to a UMD global, but the current file is a module. Consider adding an import instead.
button
onClick={const disconnectWallet: () => voiddisconnectWallet}>Disconnect</button>
</div> )} </div> ); } export default function App(): React.JSX.ElementApp;

For environment variables in Vite, use the VITE_ prefix:

# .env
VITE_SWAPKIT_API_KEY=your_api_key_here
VITE_WALLETCONNECT_PROJECT_ID=your_project_id_here

Then configure SwapKit:

import { 
function createSwapKit(config?: Parameters<typeof SwapKit>[0]): {
    chainflip: {
        supportedSwapkitProviders: ProviderName[];
    } & {
        swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
    };
    ... 5 more ...;
    near: {
        ...;
    } & {
        ...;
    };
} & {
    ...;
} & {
    ...;
}
createSwapKit
,
const SKConfig: {
    getState: () => SwapKitConfigStore;
    get: <T extends "wallets" | "apiKeys" | "apis" | "chains" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations">(key: T) => SwapKitConfigStore[T];
    ... 6 more ...;
    setIntegrationConfig: <T extends keyof SKConfigIntegrations>(integration: T, config: SKConfigIntegrations[T]) => void;
}
SKConfig
} from '@swapkit/sdk';
// Configure API keys
const SKConfig: {
    getState: () => SwapKitConfigStore;
    get: <T extends "wallets" | "apiKeys" | "apis" | "chains" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations">(key: T) => SwapKitConfigStore[T];
    ... 6 more ...;
    setIntegrationConfig: <T extends keyof SKConfigIntegrations>(integration: T, config: SKConfigIntegrations[T]) => void;
}
SKConfig
.setApiKey: <"swapKit">(key: "swapKit", apiKey: string) => voidsetApiKey('swapKit',
Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.
import.meta.env.VITE_SWAPKIT_API_KEY
);
const SKConfig: {
    getState: () => SwapKitConfigStore;
    get: <T extends "wallets" | "apiKeys" | "apis" | "chains" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations">(key: T) => SwapKitConfigStore[T];
    ... 6 more ...;
    setIntegrationConfig: <T extends keyof SKConfigIntegrations>(integration: T, config: SKConfigIntegrations[T]) => void;
}
SKConfig
.setApiKey: <"walletConnectProjectId">(key: "walletConnectProjectId", apiKey: string) => voidsetApiKey('walletConnectProjectId',
Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.
import.meta.env.VITE_WALLETCONNECT_PROJECT_ID
);
export const
const swapKitClient: {
    chainflip: {
        supportedSwapkitProviders: ProviderName[];
    } & {
        swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
    };
    ... 5 more ...;
    near: {
        ...;
    } & {
        ...;
    };
} & {
    ...;
} & {
    ...;
}
swapKitClient
=
function createSwapKit(config?: Parameters<typeof SwapKit>[0]): {
    chainflip: {
        supportedSwapkitProviders: ProviderName[];
    } & {
        swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
    };
    ... 5 more ...;
    near: {
        ...;
    } & {
        ...;
    };
} & {
    ...;
} & {
    ...;
}
createSwapKit
();

If you encounter WebAssembly-related errors, ensure you have the required plugins installed:

bun add -D vite-plugin-wasm vite-plugin-top-level-await

For a complete working example, check out the Vite playground in the SwapKit repository.