Code Monkey home page Code Monkey logo

fingerprintjs / fingerprintjs-pro-server-api-node-sdk Goto Github PK

View Code? Open in Web Editor NEW
18.0 9.0 3.0 1.09 MB

Node.js wrapper for FingerprintJS Server API

Home Page: https://dev.fingerprintjs.com/docs/server-api

License: MIT License

TypeScript 92.42% JavaScript 5.97% Shell 1.61%
api-wrapper audio-fingerprinting browser browser-fingerprint browser-fingerprinting detection fingerprint fingerprinting fingerprintjs fingerprintjs-pro fraud fraud-detection identification javascript nodejs nodejs-server visitor-identification

fingerprintjs-pro-server-api-node-sdk's Introduction

Fingerprint logo

Build status coverage Current NPM version Monthly downloads from NPM Discord server

Fingerprint Server API Node.js SDK

Fingerprint is a device intelligence platform offering 99.5% accurate visitor identification.

The Fingerprint Server Node SDK is an easy way to interact with the Fingerprint Server API from your Node application. You can retrieve visitor history or individual identification events.

Requirements

TypeScript support:

  • TypeScript 4.5.5 or higher

Supported runtimes:

  • Node.js 18 LTS or higher (we support all Node LTS releases before end-of-life).

  • Deno and Bun might work but are not actively tested.

  • "Edge" runtimes might work with some modifications but are not actively tested.

    See "edge" runtimes compatibility

    This SDK can be made compatible with JavaScript "edge" runtimes that do not support all Node APIs, for example, Vercel Edge Runtime, or Cloudflare Workers.

    To make it work, replace the SDK's built-in fetch function (which relies on Node APIs) with the runtime's native fetch function. Pass the function into the constructor with proper binding:

    const client = new FingerprintJsServerApiClient({
      region: Region.EU,
      apiKey: apiKey,
      fetch: fetch.bind(globalThis),
    })

How to install

Install the package using your favorite package manager:

  • NPM:

    npm i @fingerprintjs/fingerprintjs-pro-server-api
  • Yarn:

    yarn add @fingerprintjs/fingerprintjs-pro-server-api
  • pnpm:

    pnpm i @fingerprintjs/fingerprintjs-pro-server-api

Getting started

Initialize the client instance and use it to make API requests. You need to specify your Fingerprint Secret API key and the region of your Fingerprint application.

import {
  FingerprintJsServerApiClient,
  Region,
} from '@fingerprintjs/fingerprintjs-pro-server-api'

const client = new FingerprintJsServerApiClient({
  apiKey: '<SECRET_API_KEY>',
  region: Region.Global,
})

// Get visit history of a specific visitor
client.getVisitorHistory('<visitorId>').then((visitorHistory) => {
  console.log(visitorHistory)
})

// Get a specific identification event
client.getEvent('<requestId>').then((event) => {
  console.log(event)
})

See the Examples folder for more detailed examples.

Error handling

The Server API methods like getEvent and getVisitorHistory can throw EventError and VisitorsError. You can use the provided isVisitorsError and isEventError type guards to narrow down error types:

import {
  isVisitorsError,
  isEventError,
  FingerprintJsServerApiClient,
} from '@fingerprintjs/fingerprintjs-pro-server-api'

const client = new FingerprintJsServerApiClient({
  apiKey: '<SECRET_API_KEY>',
  region: Region.Global,
})

// Handling getEvent errors
try {
  const event = await client.getEvent(requestId)
  console.log(JSON.stringify(event, null, 2))
} catch (error) {
  if (isEventError(error)) {
    console.log(error.response) // You can also access the raw response
    console.log(`error ${error.status}: `, error.error?.message)
  } else {
    console.log('unknown error: ', error)
  }
}

// Handling getVisitorHistory errors
try {
  const visitorHistory = await client.getVisitorHistory(visitorId, {
    limit: 10,
  })
  console.log(JSON.stringify(visitorHistory, null, 2))
} catch (error) {
  if (isVisitorsError(error)) {
    console.log(error.status, error.error)
    if (error.status === 429) {
      retryLater(error.retryAfter) // Needs to be implemented on your side
    }
  } else {
    console.error('unknown error: ', error)
  }
}

Webhooks

Webhook types

When handling Webhooks coming from Fingerprint, you can cast the payload as the built-in VisitWebhook type:

import { VisitWebhook } from '@fingerprintjs/fingerprintjs-pro-server-api'

const visit = visitWebhookBody as unknown as VisitWebhook

Webhook signature validation

Customers on the Enterprise plan can enable Webhook signatures to cryptographically verify the authenticity of incoming webhooks. This SDK provides a utility method for verifying the HMAC signature of the incoming webhook request.

To learn more, see example/validateWebhookSignature.mjs or read the API Reference.

Sealed results

Customers on the Enterprise plan can enable Sealed results to receive the full device intelligence result on the client and unseal it on the server. This SDK provides utility methods for decoding sealed results.

To learn more, see example/unsealResult.mjs or the API Reference.

Deleting visitor data

Customers on the Enterprise plan can Delete all data associated with a specific visitor to comply with privacy regulations. See example/deleteVisitor.mjs or the API Reference.

API Reference

See the full API reference.

Support and feedback

To report problems, ask questions, or provide feedback, please use Issues. If you need private support, you can email us at [email protected].

License

This project is licensed under the MIT license.

fingerprintjs-pro-server-api-node-sdk's People

Contributors

dependabot[bot] avatar ilfa avatar jurouhlar avatar makma avatar necipallef avatar orkuncakilkaya avatar semantic-release-bot avatar theunderscorer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fingerprintjs-pro-server-api-node-sdk's Issues

The automated release is failing 🚨

🚨 The automated release from the main branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the main branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Expose `Visit` data type

It would be nice if the library could expose the Visit data type.

I want to do something like

/**
 * @param { import('@fingerprintjs/fingerprintjs-pro-server-api').Visit} visitData - does't work 
 */
function checkSomethingInVisitData (visitData) {
  console.log(visitData.ipLocation.city);
} 

Where Visit corresponds to the components.schemas.Visit in the provided index.d.ts. But I can't because Visit is not exposed directly.

Adding declare type Visit = components['schemas']['Visit']; and removing [] brackets from Visit in the schema might be sufficient. Thank you!

Make throwing errors on non-200 responses optional

This is just a suggestion on how to make the API slightly more ergonomic for some users (partially subjective).

I was trying to validate a requestId, I did not check the SDK docs, I was just testing the API in Postman and my first instinct was to do it like this:

 const client = new FingerprintJsServerApiClient({ region: Region.Global, apiKey: SERVER_API_KEY });
    const eventResponse = await client.getEvent(requestId);

    // TS Error: Property 'error' does not exist on type '{ products?: { identification?: ....
    if ( eventResponse.error) {
    ...

The reason this does not work is that any non-200 response is caught as thrown as an error, so checking for non-existing requestId must be done on the error object inside a catch block. This works and is documented, but I think it might be unexpected to at least some portion of users. The natural expectation is that the SDK is just a wrapper over fetch and fetch only throws errors when the request itself fails (just extrapolating from my own experience here).

Sometimes, I totally expect the server to tell me it didn't find what I was looking for and it's not great DX to deal with that in a catch block:

  • It breaks the natural logic flow
  • The error object inside catch is not properly typed, so I need to figure out its shape using docs/experiments.

axios behaves the same way, but people found it confusing and they eventually fixed it by providing a validateStatus config option to turn the errors off.

Something potentially worth considering here as well (not necessarily making a breaking change but providing a way to change the default behavior).

The getEvent method could then return Promise<EventResponse | ErrorResponse> (same for getVisitorHistory) which would naturally nudge users to check for a non-200 response in a type-safe way (something that they need to do for every single use case).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.