mirror of
https://github.com/better-auth/better-auth.git
synced 2026-06-05 13:56:30 -05:00
48 lines
1.8 KiB
Plaintext
48 lines
1.8 KiB
Plaintext
---
|
|
title: Node Integration
|
|
description: Integrate Better Auth with Node backend
|
|
---
|
|
|
|
Better Auth can be integrated with node based backed frameworks. The guide below will show you how to integrate Better Auth with express.
|
|
|
|
Before you start, make sure you have a Better Auth instance configured. If you haven't done that yet, check out the [installation](/docs/installation).
|
|
|
|
### Mount the handler
|
|
|
|
To enable Better Auth to handle requests, we need to mount the handler to an API route. Create a catch-all route to manage all requests to `/api/auth/*` (or any other path specified in your Better Auth options).
|
|
|
|
```ts title="server.ts"
|
|
import express from "express";
|
|
import { toNodeHandler } from "better-auth/node";
|
|
import { auth } from "./auth";
|
|
|
|
const app = express();
|
|
const port = 3005;
|
|
|
|
app.all("/api/auth/*", toNodeHandler(auth));
|
|
|
|
app.listen(port, () => {
|
|
console.log(`Example app listening on port ${port}`);
|
|
});
|
|
```
|
|
|
|
After completing the setup, start your server. Better Auth will be ready to use. You can send a `GET` request to the `/ok` endpoint (`/api/auth/ok`) to verify that the server is running.
|
|
|
|
### Getting the User Session
|
|
|
|
To retrieve the user's session, you can use the `getSession` method provided by the `auth` object. This method requires the request headers to be passed in a specific format. To simplify this process, Better Auth provides a `fromNodeHeaders` helper function that converts Node.js request headers to the format expected by Better Auth (a `Headers` object).
|
|
|
|
Here's an example of how to use `getSession` in an Express route:
|
|
|
|
```ts title="server.ts"
|
|
import { fromNodeHeaders } from "better-auth/node";
|
|
import { auth } from "./auth"; //your better auth instance
|
|
|
|
app.get("/api/me", async (req, res) => {
|
|
const session = await auth.getSession({
|
|
headers: fromNodeHeaders(req.headers),
|
|
});
|
|
return res.json(session);
|
|
});
|
|
```
|