Unverified Commit a4117c94 authored by Ilya Taratukhin's avatar Ilya Taratukhin Committed by GitHub

Adding example with-fingerprintjs-pro for identifying visitors (#37549)



## Documentation / Examples

- [x] Make sure the linting passes by running `pnpm lint`
- [x] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)

Deployed on https://with-fingerprintjs-pro.vercel.app/
parent 4dfe5634
NEXT_PUBLIC_FPJS_PUBLIC_API_KEY=<your_fingerprintjs_pro_public_key>
\ No newline at end of file
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local
# vercel
.vercel
# typescript
*.tsbuildinfo
# An example app with FingerprintJS Pro
This example shows how to identify visitors using [FingerprintJS Pro](https://fingerprintjs.com/) with Next.js.
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-fingerprintjs-pro&project-name=with-fingerprintjs-pro&repository-name=with-fingerprintjs-pro)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:
```bash
npx create-next-app --example with-fingerprintjs-pro with-fingerprintjs-pro-app
# or
yarn create next-app --example with-fingerprintjs-pro with-fingerprintjs-pro-app
# or
pnpm create next-app --example with-fingerprintjs-pro with-fingerprintjs-pro-app
```
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
## Notes
### API key
To identify visitors, you'll need a FingerprintJS Pro account (you can [sign up for free](https://dashboard.fingerprintjs.com/signup/)).
You can learn more about API keys in the [official FingerprintJS Pro documentation](https://dev.fingerprintjs.com/docs/quick-start-guide).
Once you get public key, you need to set up the API key in the environment variable `NEXT_PUBLIC_FPJS_PUBLIC_API_KEY`.
import { useRouter } from 'next/router'
export const CacheStrategySelector = () => {
const router = useRouter()
const { asPath, route } = router
const value = asPath.split('/')[2]
return (
<div className="cache-option-toggler">
<h4>Cache option</h4>
<select
name="cache-option"
onChange={(event) => {
const newValue = event.currentTarget.value
const newRoute = route.replace('[cacheStrategy]', newValue)
router.push(newRoute, undefined, { scroll: false })
}}
value={value}
>
<option value="no-cache">Without cache</option>
<option value="memory-cache">Memory Cache</option>
<option value="session-storage-cache">Session Storage Cache</option>
<option value="ls-cache">Local Storage Cache</option>
</select>
</div>
)
}
import { PropsWithChildren } from 'react'
import { useRouter } from 'next/router'
import Link from 'next/link'
import { RouterProps } from './types'
export const Nav: React.FC = () => {
return (
<nav className="nav">
<CustomLink to="home">Home</CustomLink>
<CustomLink to="signin">Sign in</CustomLink>
</nav>
)
}
const CustomLink: React.FC<PropsWithChildren<{ to: string }>> = ({
to,
children,
}) => {
const router = useRouter()
const { pathname } = router
const { cacheStrategy } = router.query as RouterProps
const linkPathname = `/${to}/[cacheStrategy]`
const className = `nav-link${pathname === linkPathname ? ' active' : ''}`
return (
<div>
<Link
href={{
pathname: linkPathname,
query: { cacheStrategy },
}}
scroll={false}
>
<a className={className}>{children}</a>
</Link>
</div>
)
}
import { PropsWithChildren, useState } from 'react'
function Toggler({ children }: PropsWithChildren<{}>) {
const [showChildren, setShowChildren] = useState(true)
return (
<div className="toggler">
<p>
You can open the Network tab in your browser Dev Tools and see new
requests being made depending on the <b>caching algorithm</b> as you
unmount the component with the fingerprint and mount it again thus
calling the <code>useVisitorData</code> hook.
</p>
<button
className="toggle-button"
onClick={() => setShowChildren((show) => !show)}
>
{showChildren ? 'Hide' : 'Show'} visitor data
</button>
{showChildren && children}
</div>
)
}
export default Toggler
import { VisitorData } from '@fingerprintjs/fingerprintjs-pro-react'
function VisitorDataPresenter({
data,
isLoading,
error,
}: {
data?: VisitorData
isLoading?: boolean
error?: Error
}) {
if (error) {
return <p>An error occurred: {error.message}</p>
}
return (
<div className="visitor-data">
<p>
<b>Visitor ID:</b>{' '}
{isLoading
? 'Loading...'
: data
? data.visitorId
: 'not established yet'}
</p>
{data && (
<>
<p>
<b>Full visitor data:</b>
</p>
<pre className="details">{JSON.stringify(data, null, 2)}</pre>
</>
)}
</div>
)
}
export default VisitorDataPresenter
export type CacheStrategyPath =
| 'no-cache'
| 'memory-cache'
| 'session-storage-cache'
| 'ls-cache'
export type RouterProps = {
cacheStrategy: CacheStrategyPath
}
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
async redirects() {
return [
{
source: '/',
destination: '/home/memory-cache',
permanent: true,
},
]
},
}
module.exports = nextConfig
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"@fingerprintjs/fingerprintjs-pro-react": "1.0.1",
"next": "latest",
"react": "18.1.0",
"react-dom": "18.1.0"
},
"devDependencies": {
"@types/node": "17.0.40",
"@types/react": "18.0.12",
"typescript": "4.7.3"
}
}
import { useRouter } from 'next/router'
import Head from 'next/head'
import '../styles/globals.css'
import '../styles/App.css'
import { InMemoryCache } from '../providers/InMemoryCache'
import { LocalStorageCache } from '../providers/LocalStorageCache'
import { WithoutCache } from '../providers/WithoutCache'
import { SessionStorageCache } from '../providers/SessionStorageCache'
import { CacheStrategySelector } from '../components/CacheStrategySelector'
import { Nav } from '../components/Nav'
import type { AppProps } from 'next/app'
import type { CacheStrategyPath, RouterProps } from '../components/types'
const getFingerprintJsProProviderByCacheStrategy = (
cacheStrategy: CacheStrategyPath
) => {
switch (cacheStrategy) {
case 'no-cache':
return WithoutCache
case 'ls-cache':
return LocalStorageCache
case 'session-storage-cache':
return SessionStorageCache
default:
return InMemoryCache
}
}
function MyApp({ Component, pageProps }: AppProps) {
const router = useRouter()
const { cacheStrategy } = router.query as RouterProps
const ConfiguredFingerprintJsProProvider =
getFingerprintJsProProviderByCacheStrategy(cacheStrategy)
return (
<div className="layout">
<Head>
<title>FingerprintJs Pro example for Next.js</title>
</Head>
<CacheStrategySelector />
<main>
<ConfiguredFingerprintJsProProvider>
<Nav />
<Component {...pageProps} />
</ConfiguredFingerprintJsProProvider>
</main>
</div>
)
}
export default MyApp
import Toggler from '../../components/Toggler'
import VisitorDataPresenter from '../../components/VisitorDataPresenter'
import { useContext } from 'react'
import {
FpjsContext,
useVisitorData,
} from '@fingerprintjs/fingerprintjs-pro-react'
function HomePage() {
const { clearCache } = useContext(FpjsContext)
return (
<section className="body">
<h3>Home page</h3>
<div>
On this page we use the <code>useVisitorData</code> hook with default
settings and identification is performed as soon as the page loads. This
is the most common use-case.
</div>
<Toggler>
<VisitorDataComponent />
</Toggler>
<button className="clear-cache-button" onClick={() => clearCache()}>
Clear cache
</button>
</section>
)
}
function VisitorDataComponent() {
const { data, isLoading, error } = useVisitorData({ extendedResult: true })
return (
<VisitorDataPresenter data={data} isLoading={isLoading} error={error} />
)
}
export default HomePage
import { useState } from 'react'
import { useVisitorData } from '@fingerprintjs/fingerprintjs-pro-react'
import VisitorDataPresenter from '../../components/VisitorDataPresenter'
function SignInPage() {
const [login, setLogin] = useState('')
const [password, setPassword] = useState('')
const [tag, setTag] = useState('')
const [ignoreCache, setIgnoreCache] = useState(false)
const [extendedResult, setExtendedResult] = useState(false)
const { getData, data, isLoading, error } = useVisitorData(
{ extendedResult, tag, linkedId: login },
{ immediate: false }
)
return (
<section className="body">
<h3>Sign in</h3>
<div>
<p>
Another common use-case is when you want to only fingerprint a user
after they perform some action, in this case - submit a form. For this
purpose <code>useVisitorData</code> hook should be called with{' '}
<code>immediate</code> flag set to <code>false</code> and call the{' '}
<code>getData</code> function on form submission.
</p>
<p>
Try submitting the form with any values and notice that a fingerprint
will be calculated.
</p>
</div>
<div className="form-control checkbox">
<label htmlFor="ignore-cache">
Ignore cache:
<input
id="ignore-cache"
type="checkbox"
checked={ignoreCache}
onChange={(e) => setIgnoreCache(e.currentTarget.checked)}
/>
</label>
</div>
<div className="form-control checkbox">
<label htmlFor="extended-result">
Extended result:
<input
id="extended-result"
type="checkbox"
checked={extendedResult}
onChange={(e) => setExtendedResult(e.currentTarget.checked)}
/>
</label>
<sub>will be used as extended_result param for the request</sub>
</div>
<form
className="form"
onSubmit={(e) => {
e.preventDefault()
getData({ ignoreCache }).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)
}
})
}}
>
<div className="form-control">
<label htmlFor="login">Login:</label>
<input
id="login"
type="text"
name="login"
required
autoComplete="off"
value={login}
onChange={(e) => setLogin(e.currentTarget.value)}
/>
<sub>will be used as linked_id param for the request</sub>
</div>
<div className="form-control">
<label htmlFor="password">Password:</label>
<input
id="password"
type="password"
name="password"
required
value={password}
onChange={(e) => setPassword(e.currentTarget.value)}
/>
</div>
<div className="form-control">
<label htmlFor="tag">Tag:</label>
<input
id="tag"
type="text"
name="tag"
value={tag}
onChange={(e) => setTag(e.currentTarget.value)}
/>
<sub>will be used as tag param for the request</sub>
</div>
<button type="submit">Submit</button>
</form>
<VisitorDataPresenter data={data} isLoading={isLoading} error={error} />
</section>
)
}
export default SignInPage
import { PropsWithChildren } from 'react'
import {
CacheLocation,
FpjsProvider,
LoadOptions,
} from '@fingerprintjs/fingerprintjs-pro-react'
const fpjsPublicApiKey = process.env.NEXT_PUBLIC_FPJS_PUBLIC_API_KEY as string
export const InMemoryCache: React.FC<PropsWithChildren> = ({ children }) => {
const loadOptions: LoadOptions = {
apiKey: fpjsPublicApiKey,
}
return (
<FpjsProvider
loadOptions={loadOptions}
cacheLocation={CacheLocation.Memory}
>
<div className="App">
<header className="header">
<h2>Solution with an in-memory cache</h2>
<div className="subheader">
New API call made after a key expires, a page is reloaded or the
provider is unmounted
</div>
</header>
{children}
</div>
</FpjsProvider>
)
}
import { PropsWithChildren } from 'react'
import {
CacheLocation,
FpjsProvider,
LoadOptions,
} from '@fingerprintjs/fingerprintjs-pro-react'
const fpjsPublicApiKey = process.env.NEXT_PUBLIC_FPJS_PUBLIC_API_KEY as string
export const LocalStorageCache: React.FC<PropsWithChildren> = ({
children,
}) => {
const loadOptions: LoadOptions = {
apiKey: fpjsPublicApiKey,
}
return (
<FpjsProvider
loadOptions={loadOptions}
cacheLocation={CacheLocation.LocalStorage}
cachePrefix="MY_AWESOME_PREFIX"
cacheTimeInSeconds={60 * 10}
>
<div className="App">
<header className="header">
<h2>Solution with a local storage cache</h2>
<div className="subheader">
New API call made after a key expires or is cleared from the local
storage
</div>
</header>
{children}
</div>
</FpjsProvider>
)
}
import { PropsWithChildren } from 'react'
import {
CacheLocation,
FpjsProvider,
LoadOptions,
} from '@fingerprintjs/fingerprintjs-pro-react'
const fpjsPublicApiKey = process.env.NEXT_PUBLIC_FPJS_PUBLIC_API_KEY as string
export const SessionStorageCache: React.FC<PropsWithChildren> = ({
children,
}) => {
const loadOptions: LoadOptions = {
apiKey: fpjsPublicApiKey,
}
return (
<FpjsProvider
loadOptions={loadOptions}
cacheLocation={CacheLocation.SessionStorage}
cacheTimeInSeconds={60 * 5}
>
<div className="App">
<header className="header">
<h2>
Solution with a custom implementation of a session storage cache
</h2>
<div className="subheader">
New API call made after a key expires or is cleared from the local
storage
</div>
</header>
{children}
</div>
</FpjsProvider>
)
}
import { PropsWithChildren } from 'react'
import {
CacheLocation,
FpjsProvider,
LoadOptions,
} from '@fingerprintjs/fingerprintjs-pro-react'
const fpjsPublicApiKey = process.env.NEXT_PUBLIC_FPJS_PUBLIC_API_KEY as string
export const WithoutCache: React.FC<PropsWithChildren> = ({ children }) => {
const loadOptions: LoadOptions = {
apiKey: fpjsPublicApiKey,
}
return (
<FpjsProvider
loadOptions={loadOptions}
cacheLocation={CacheLocation.NoCache}
>
<div className="App">
<header className="header">
<h2>Solution without cache</h2>
<div className="subheader">
New API call made on every component render
</div>
</header>
{children}
</div>
</FpjsProvider>
)
}
h2,
h3 {
margin-top: 12px;
margin-bottom: 12px;
}
code {
background-color: rgba(255, 229, 100, 0.2);
padding: 0 3px;
font-size: 0.94em;
word-break: break-word;
}
sub {
color: rgba(0, 0, 0, 0.47);
}
.header {
padding: 8px 0;
margin-bottom: 12px;
max-width: 70%;
}
.subheader {
font-size: 16px;
margin-top: 12px;
margin-bottom: 12px;
}
.layout {
position: relative;
max-width: 75%;
margin: 36px auto 0;
}
.nav {
margin: 12px auto 12px 16px;
display: flex;
align-items: center;
gap: 4px;
padding-top: 8px;
}
.nav .nav-link {
text-decoration: none;
cursor: pointer;
padding: 12px;
color: #000000;
border: 2px solid #777777;
border-bottom: none;
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
.nav .nav-link.active {
text-decoration: none;
cursor: pointer;
padding: 12px;
color: #fff;
background-color: #777777;
border: 2px solid #777777;
border-bottom: none;
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
.toggler {
margin-top: 16px;
margin-bottom: 16px;
}
.cache-option-toggler {
position: absolute;
top: 24px;
right: 0;
background-color: #2d357a;
color: #fff;
border-radius: 4px;
padding: 8px 16px 12px;
border: 1px solid black;
}
.cache-option-toggler h4 {
margin: 8px auto 16px;
font-weight: 500;
}
.cache-option-toggler select {
cursor: pointer;
padding: 4px;
}
.body {
min-height: 48vh;
border: 2px solid #777777;
padding: 12px 24px;
border-radius: 4px;
}
.form {
margin-top: 20px;
max-width: 300px;
}
.form-control {
display: flex;
flex-direction: column;
margin-bottom: 16px;
}
.form-control.checkbox {
display: flex;
flex-direction: column;
margin-bottom: 12px;
}
.form-control label {
font-weight: 500;
}
.form-control input {
margin-top: 8px;
font-size: 18px;
}
.form button[type='submit'] {
padding: 8px 12px;
font-size: 16px;
cursor: pointer;
background-color: #ff5d22;
border-radius: 4px;
border: none;
color: #fff;
}
.toggle-button {
padding: 8px 12px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
background-color: #ff5d22;
color: #fff;
border-radius: 4px;
border: none;
}
.visitor-data {
margin-top: 16px;
margin-bottom: 16px;
}
.visitor-data .details {
max-height: 200px;
overflow: scroll;
}
.clear-cache-button {
cursor: pointer;
}
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: rgba(0, 0, 0, 0.87);
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment