Hono Integration
Before you start, make sure you have a Better Auth instance configured. If you haven't done that yet, check out the installation.
Mount the handler
We need to mount the handler to Hono endpoint.
Cors
To configure cors, you need to use the cors
plugin from hono/cors
.
Middleware
You can add a middleware to save the session
and user
in a context
and also add validations for every route.
This will allow you to access the user
and session
object in all of your routes.
Cross-Domain Cookies
By default, all Better Auth cookies are set with SameSite=Lax
. If you need to use cookies across different domains, you’ll need to set SameSite=None
and Secure=true
. However, we recommend using subdomains whenever possible, as this allows you to keep SameSite=Lax
. To enable cross-subdomain cookies, simply turn on crossSubDomainCookies
in your auth config.
If you still need to set SameSite=None
and Secure=true
, you can adjust these attributes globally through cookieOptions
in the createAuth
configuration.
You can also customize cookie attributes individually by setting them within cookies
in your auth config.
Client-Side Configuration
When using the Hono client (@hono/client
) to make requests to your Better Auth-protected endpoints, you need to configure it to send credentials (cookies) with cross-origin requests.
This configuration is necessary when:
- Your client and server are on different domains/ports during development
- You're making cross-origin requests in production
- You need to send authentication cookies with your requests
The credentials: "include"
option tells the fetch client to send cookies even for cross-origin requests. This works in conjunction with the CORS configuration on your server that has credentials: true
.
Note: Make sure your CORS configuration on the server matches your client's domain, and that
credentials: true
is set in both the server's CORS config and the client's fetch config.