Usage

NextJS Integration

Learn how to use the Nimiq Web Client in your NextJS application

NextJS Integration

The Nimiq Web Client ships with built-in support for NextJS applications. Here's how to get started:

Installation

npm install @nimiq/core

Basic Usage

Create a new client component:

'use client';
 
import { useState, useEffect } from 'react';
import { Client, ClientConfiguration } from '@nimiq/core';
 
export default function NimiqClient() {
  const [isConnected, setIsConnected] = useState(false);
 
  useEffect(() => {
    async function initClient() {
      try {
        const config = new ClientConfiguration();
        const client = await Client.create(config.build());
        
        await client.waitForConsensusEstablished();
        setIsConnected(true);
        
        // Subscribe to blockchain updates
        client.addHeadChangedListener((head) => {
          console.log('New block:', head.height);
        });
      } catch (error) {
        console.error('Failed to initialize Nimiq client:', error);
      }
    }
 
    initClient();
  }, []);
 
  return (
    <div>
      Status: {isConnected ? 'Connected' : 'Connecting...'}
    </div>
  );
}

Always use the 'use client' directive when working with the Nimiq Web Client in NextJS components.

Configuration Options

You can customize the client configuration:

const config = new ClientConfiguration()
  .withNetwork('test') // 'main' or 'test'
  .withConsensus('light') // 'light' or 'full'
  .withAutoConnect(true)
  .build();
 
const client = await Client.create(config);

Best Practices

  1. Client Components: Always use client components when interacting with the Nimiq Web Client
  2. Error Handling: Implement proper error handling for network issues
  3. Cleanup: Remember to remove event listeners in useEffect cleanup functions
  4. State Management: Consider using React Context for sharing client instances

Example with Context

'use client';
 
import { createContext, useContext, useEffect, useState } from 'react';
import { Client, ClientConfiguration } from '@nimiq/core';
 
const NimiqContext = createContext<Client | null>(null);
 
export function NimiqProvider({ children }) {
  const [client, setClient] = useState<Client | null>(null);
 
  useEffect(() => {
    async function init() {
      const config = new ClientConfiguration();
      const newClient = await Client.create(config.build());
      await newClient.waitForConsensusEstablished();
      setClient(newClient);
    }
 
    init();
  }, []);
 
  return (
    <NimiqContext.Provider value={client}>
      {children}
    </NimiqContext.Provider>
  );
}
 
export function useNimiq() {
  const client = useContext(NimiqContext);
  if (!client) throw new Error('useNimiq must be used within NimiqProvider');
  return client;
}

The Web Client requires a browser environment. Make sure your components using it are properly marked as client components.

On this page