# Next.js (/docs/adapters/nextjs)

## Installation

`xmcp` can work on top of your existing Next.js project. To get started, run the following command in your project directory:

```bash
npx init-xmcp@latest
```

On initialization, you'll see the following prompts:

<TerminalPrompt>
  {
      "? Tools directory path: (tools)\n? Prompts directory path: (prompts)\n? Resources directory path: (resources)\n? Route directory path: (app/mcp)"
  }
</TerminalPrompt>

The package manager and framework will be detected automatically.

After setting up the project, your build and dev commands should look like this:

```json
{
  "scripts": {
    "dev": "xmcp dev & next dev",
    "build": "xmcp build && next build"
  }
}
```

<Callout variant="info">
  Before using the `@xmcp/adapter` import, you need to:

  1. Run `npx xmcp build` to generate the `.xmcp` folder
  2. Update your `tsconfig.json` to include the path mapping:

  ```json title="tsconfig.json"
  {
    "compilerOptions": {
      "paths": {
        "@xmcp/*": ["./.xmcp/*"]
      }
    }
  }
  ```

  After these steps, TypeScript errors will be resolved.
</Callout>

Based on your configuration, it will create the tools, prompts, resources and route folders and add an endpoint to your Next.js app.

```typescript title="app/mcp/route.ts"
import { xmcpHandler } from "@xmcp/adapter";

export { xmcpHandler as GET, xmcpHandler as POST };
```

<Callout variant="info">
  `middleware.ts` and `xmcp/headers` are not supported since Next.js already
  supports those features.
</Callout>

## Authentication

You can use the `withAuth` function to add authentication to your MCP server.

```typescript title="app/mcp/route.ts"
import { xmcpHandler, withAuth, VerifyToken } from "@xmcp/adapter";

/**
 * Verify the bearer token and return auth information
 * In a real implementation, this would validate against your auth service
 */
const verifyToken: VerifyToken = async (req: Request, bearerToken?: string) => {
  if (!bearerToken) return undefined;

  // TODO: Replace with actual token verification logic
  // This is just an example implementation
  const isValid = bearerToken.startsWith("__TEST_VALUE__");

  if (!isValid) return undefined;

  return {
    token: bearerToken,
    scopes: ["read:messages", "write:messages"],
    clientId: "example-client",
    extra: {
      userId: "user-123",
      // Add any additional user/client information here
      permissions: ["user"],
      timestamp: new Date().toISOString(),
    },
  };
};

const options = {
  verifyToken,
  required: true,
  requiredScopes: ["read:messages"],
  resourceMetadataPath: "/.well-known/oauth-protected-resource",
};

const handler = withAuth(xmcpHandler, options);

export { handler as GET, handler as POST };
```
