Next.js How to integrate the Split SDK into applications using Next.js.
Setup
Install the SDK using npm or yarn.
Copy # node
npm install @split-tech/browser-sdk
# yarn
yarn add @split-tech/browser-sdk
Ensure your environment has Node.js version 18.0.0 or higher before installing the SDK.
Example
In your Next.js _app.tsx
file, import and initialize the Split SDK like this.
Using SplitBrowserProvider
Copy // _app.tsx
import type { AppProps } from "next/app" ;
import { SplitBrowserProvider , type SplitProviderConfig } from "@split-tech/browser-sdk" ;
const config : SplitProviderConfig = {
referralParam : "code" ,
refetchInterval : 3000
};
const App = ({ Component , pageProps: { sessions , ... pageProps } } : AppProps ) =>
return (
< SplitBrowserProvider apiKey = { YOUR_API_KEY } config = {config}>
< Component { ... pageProps} />
</ SplitBrowserProvider >
)
};
export default App;
Using built-in functions.
By utilizing built-in functions like init
and addReferral
within the provider.
Copy // _app.tsx
import { type SplitConfig } from "@split-tech/browser-sdk" ;
import { Split } from "../contexts/SplitContext" ;
const config : SplitConfig = {
referralParam : "code"
};
Split .initialize ();
const App = ({ Component , pageProps: { sessions , ... pageProps } } : AppProps ) => {
return (
< SplitProvider >
< Component { ... pageProps} />
</ SplitProvider >
)
};
export default App;
Creating Custom SplitProvider
Copy // contexts/SplitContext.tsx
import React , { createContext , useContext } from "react" ;
import { init , addReferral , SplitConfig } from "@split-tech/browser-sdk" ;
export const Split = {
initialize : async () => {
await init ( process . env . SPLIT_API_KEY ?? "" , config)
} ,
addReferral : async (walletAddress : string ) => {
await addReferral (walletAddress)
}
};
export const SplitContext = createContext < typeof Split>(Split);
const SplitProvider = ({ children } : PropsWithChildren ) => {
const [ address , setAddress ] = useState ( "" );
useEffect (() => {
addReferral (address)
} , [])
return (
< SplitContext.Provider value = {Split}>
{children}
< SplitContext.Provider >
)
}l
export const useSplit = () => useContext(SplitContext);
If you want to automatically track wallet addresses, please execute addReferral
within useEffect
. To manually send wallet addresses to the Split server when needed, please use the following method.
Using Split Hook Method in a Component
Copy
// pages/index.tsx
import { useSplit } from "../../contexts/SplitContext"
const TestPage = () => {
const { addReferral } = useSplit ();
const [ address , setAddress ] = useState ( "" );
const handleClick = async () => {
await addReferral (address);
};
return (
< div >
< input name = "referee" value = {address} onChange = {(e) => setAddress ( e . target .value)}/>
< button type = "button" onClick = {handleClick}>Connect Wallet</ button >
</ div >
)
}
export default TestPage;
Last updated 4 months ago