/fingerprintjs-pro-react

FingerprintJS Pro Wrapper for React Single Page Applications (SPA)

Primary LanguageTypeScriptMIT LicenseMIT

FingerprintJS

CI badge Current NPM version Monthly downloads from NPM MIT license Discord server

FingerprintJS Pro React

FingerprintJS Pro React is an easy-to-use React library for FingerprintJS Pro. It's also compatible with the Next.js framework. SPA and Next.js examples are located in the examples folder. This package works with FingerprintJS Pro, it is not compatible with open-source FingerprintJS. You can learn more about the difference between FingerprintJS Pro and open-source FingerprintJS in the official documentation.

Table of contents

Installation

Using npm:

npm install @fingerprintjs/fingerprintjs-pro-react

Using yarn:

yarn add @fingerprintjs/fingerprintjs-pro-react

Getting started

In order to identify visitors, you'll need a FingerprintJS Pro account (you can sign up for free). You can learn more about API keys in the official FingerprintJS Pro documentation.

  1. Wrap your application (or component) in FpjsProvider. You can specify multiple configuration options.
    Set a region if you have chosen a non-global region during registration. Please refer to the Regions page.
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { FpjsProvider } from '@fingerprintjs/fingerprintjs-pro-react';
import App from './App';

ReactDOM.render(
  <FpjsProvider
    loadOptions = {{
      apiKey: 'your-fpjs-public-api-key'
    }}
  >
    <App />
  </FpjsProvider>,
  document.getElementById('app')
);
  1. Use the useVisitorData hook in your components to perform visitor identification and get the data.
// src/App.js
import React from 'react';
import { useVisitorData } from '@fingerprintjs/fingerprintjs-pro-react'

function App() {
  const {
    isLoading,
    error,
    data,
  } = useVisitorData();

  if (isLoading) {
    return <div>Loading...</div>;
  }
  if (error) {
    return <div>An error occured: {error.message}</div>;
  }

  if (data) {
    // perform some logic based on the visitor data
    return (
      <div>
        Welcome {data.visitorFound ? 'back' : ''}!
      </div>
    );
  } else {
    return null;
  }
}

export default App;

The useVisitorData hook also returns a getData method which can make an API call on your command.

// src/App.js
import React, { useState } from 'react';
import { useVisitorData } from '@fingerprintjs/fingerprintjs-pro-react'

function App() {
  const {
    isLoading,
    error,
    getData,
  } = useVisitorData({tag: 'subscription-form'}, { immediate: false });
  const [email, setEmail] = useState('')

  if (isLoading) {
    return <div>Loading...</div>;
  }
  if (error) {
    return <div>An error occured: {error.message}</div>;
  }

  return (
    <div>
      <form
        onSubmit={(e) => {
          e.preventDefault()
          getData().then((data) => {
            if (data) {
              // do something with the visitor data
              // for example, append visitor data to the form data to send to your server
              console.log(data)
            }
          })
        }}
      >
        <label htmlFor='email'>Email:</label>
        <input
          id='email'
          type='email'
          name='email'
          required
          value={email}
          onChange={(e) => setEmail(e.currentTarget.value)}
        />
        <button type='submit'>Subscribe</button>
      </form>
    </div>
  );
}

export default App;

See the full code example in the examples folder.

Caching strategy

⚠️ WARNING If you use data from extendedResult, please pay additional attention to caching strategy.

FingerprintJS Pro uses API calls as the basis for billing. Our best practices strongly recommend using cache to optimise API calls rate. The Library uses the SessionStorage cache strategy by default.

Some fields from the extendedResult (e.g ip or lastSeenAt) might change for the same visitor. If you need exact current data, it is recommended to pass ignoreCache=true inside getData function.

Documentation

This library uses FingerprintJS Pro agent internally. The documentation for the FingerprintJS Pro agent is available on https://dev.fingerprintjs.com/docs.

FpjsProvider props

loadOptions: FingerprintJS.LoadOptions

Options for the FingerprintJS JS Pro agent load() method. Options follow agent's initialisation properties.

cacheLocation?: CacheLocation

Defines which built-in cache mechanism the client should use. Caching options follow properties defined in fingerprintjs-pro-spa repository.

cache?: ICache

Custom cache implementation. Takes precedence over the cacheLocation property. Caching options follow properties defined in fingerprintjs-pro-spa repository.

cacheTimeInSeconds?: number

Duration in seconds for which data is stored in the cache. Cannot exceed 86_400 (24h) because caching data for longer than 24 hours can negatively affect identification accuracy. Caching options follow properties defined in fingerprintjs-pro-spa repository.

cachePrefix?: string

Custom prefix for localStorage and sessionStorage cache keys. Will be ignored if the cache is provided. Caching options follow properties defined in fingerprintjs-pro-spa repository.

Hooks

useVisitorData(getOptions, config)

useVisitorData hook performs identification requests with the FingerprintJS Pro API. The returned object contains information about loading status, errors, and visitor.

Params

  • getOptions: GetOptions<TExtended> parameter follows parameters of the FingerprintJS Pro's get function.
  • config: UseVisitorDataConfig's property immediate determines whether the getData() method will be called immediately after the hook mounts or not.

Returned object

  • getData: ({ignoreCache?: boolean}) => Promise<VisitorData> Performs identification request to server and returns visitors data.
  • isLoading: boolean Indicates getData request status.
  • data: VisitorData Contains visitors data requested after getData() call.
  • error: Error Error information in case the request failed.

Support and feedback

For support or to provide feedback, please raise an issue on our issue tracker. If you require private support, please email us at oss-support@fingerprintjs.com. If you'd like to have a similar React wrapper for the open-source FingerprintJS, consider raising an issue in our issue tracker.

License

This project is licensed under the MIT license. See the LICENSE file for more info.