feat(node): fromNodeHeaders helper

This commit is contained in:
Bereket Engida
2024-10-21 10:22:25 +03:00
parent a37532bcf9
commit f3abde3a30
2 changed files with 34 additions and 1 deletions

View File

@@ -26,4 +26,22 @@ app.listen(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.
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);
});
```

View File

@@ -1,6 +1,21 @@
import { toNodeHandler as toNode } from "better-call";
import type { Auth } from "../auth";
import type { IncomingHttpHeaders } from "http";
export const toNodeHandler = (auth: Auth | Auth["handler"]) => {
return "handler" in auth ? toNode(auth.handler) : toNode(auth);
};
export function fromNodeHeaders(nodeHeaders: IncomingHttpHeaders): Headers {
const webHeaders = new Headers();
for (const [key, value] of Object.entries(nodeHeaders)) {
if (value !== undefined) {
if (Array.isArray(value)) {
value.forEach((v) => webHeaders.append(key, v));
} else {
webHeaders.set(key, value);
}
}
}
return webHeaders;
}