# identify

Learn how to identify a user using a standalone function.

This method associates the current session with an identified user on the server side, serving as the equivalent of the [`identify`](/reference/sdk/javascript/api/plug/identify) method available on the client side.

You should call this method when a user authenticates, typically at login, to start a new session associated with their profile and history.

To keep the Croct token in sync with your auth system between requests, pair this with the [`userIdResolver`](with-croct#middleware-options-useridresolver-prop) option in the middleware.

## Signature

This function has the following signature:

```ts
function identify(userId: string, route?: RouteContext): Promise<void>
```

## Example

Here is an example of how to use this function:

**App router — JavaScript**

**components/LoginForm.jsx**

```jsx
'use client';

import {login} from '@/app/services';
import {identifyUser} from '@/app/actions';

export function LoginForm() {
  const onSubmit = async form => {
    const username = form.get('username');
    const password = form.get('password');

    // Your login logic
    if (await login(username, password)) {
      // Identify the user
      await identifyUser(username);
    }
  };

  return (
    <form action={onSubmit}>
      <input type="text" name="username" />
      <input type="password" name="password" />
      <button type="submit">Login</button>
    </form>
  );
};
```

**app/actions.js**

```jsx
'use server';

import {identify} from '@croct/plug-next/server';

export async function identifyUser(userId) {
  await identify(userId);
}
```

**App router — TypeScript**

**components/LoginForm.tsx**

```tsx
'use client';

import type {ReactElement} from 'react';
import {login} from '@/app/services';
import {identifyUser} from '@/app/actions';

export function LoginForm(): ReactElement {
    const onSubmit = async (form: FormData): Promise<void> => {
      const username = form.get('username');
      const password = form.get('password');

      // Your login logic
      if (await login(username, password)) {
        // Identify the user
        await identifyUser(username);
      }
    };

    return (
      <form action={onSubmit}>
        <input type="text" name="username" />
        <input type="password" name="password" />
        <button type="submit">Login</button>
      </form>
    );
};
```

**app/actions.ts**

```tsx
'use server';

import {identify} from '@croct/plug-next/server';

export async function identifyUser(userId: string): Promise<void> {
  await identify(userId);
}
```

**Page router — JavaScript**

**pages/login.js**

```jsx
export function LoginForm() {
  const onSubmit = async event => {
    event.preventDefault();

    const form = new FormData(event.currentTarget);
    const username = form.get('username');
    const password = form.get('password');

    const response = await fetch('/api/login', {
      method: 'POST',
      body: JSON.stringify({username, password}),
    });

    if (!response.ok) {
      alert('Login failed');
    }
  };

  return (
    <form onSubmit={onSubmit}>
      <input type="text" name="username" />
      <input type="password" name="password" />
      <button type="submit">Login</button>
    </form>
  );
}
```

**pages/api/login.js**

```jsx
import {login} from '@/app/services';
import {identify} from "@croct/plug-next/server";

export default async function handler(req, res) {
  const {username, password} = req.body;

  // Your login logic
  if (await login(username, password)) {
    // Identify the user
    await identify(username, {req, res});

    return res.status(200).end();
  }

  return res.status(401).end();
}
```

**Page router — TypeScript**

**pages/login.tsx**

```tsx
import type {FormEvent, ReactElement} from 'react';

export function LoginForm(): ReactElement {
  const onSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    const form = new FormData(event.currentTarget);
    const username = form.get('username');
    const password = form.get('password');

    const response = await fetch('/api/login', {
      method: 'POST',
      body: JSON.stringify({username, password}),
    });

    if (!response.ok) {
      alert('Login failed');
    }
  };

  return (
    <form onSubmit={onSubmit}>
      <input type="text" name="username" />
      <input type="password" name="password" />
      <button type="submit">Login</button>
    </form>
  );
}
```

**pages/api/login.ts**

```tsx
import type {NextApiRequest, NextApiResponse} from 'next';
import {login} from '@/app/services';
import {identify} from "@croct/plug-next/server";

export default async function handler(req: NextApiRequest, res: NextApiResponse): Promise<void> {
  const {username, password} = req.body;

    // Your login logic
  if (await login(username, password)) {
    // Identify the user
    await identify(username, {req, res});

    return res.status(200).end();
  }

  return res.status(401).end();
}
```

## Parameters

The following list describes the supported parameters:

- `userId`: `string`

  The ID that uniquely identifies the user in your application.

  Although the user ID can be any string, it is recommended to use a string or other globally unique identifier.

- `route`: `object` (optional)

  The context of the current route.

  > **Conditional requirement**
  >
  > This option is only needed for [Page router](https://nextjs.org/docs/pages) or [API routes](https://nextjs.org/docs/pages/building-your-application/routing/api-routes), as the current request scope is only accessible through the [App router](https://nextjs.org/docs/app) and [Server actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).

  The property names are aligned with those in Next.js for easy forwarding, as shown in the [Page router example](#example).

  - `req`: `NextApiRequest|NextRequest|GetServerSidePropsRequest`

    The request object.

  - `res`: `NextApiResponse|NextResponse|GetServerSidePropsResponse`

    The response object.
