Confused about Better Auth + Backend Middleware + Auth

Hey, folks Im using Better Auth for authentication on my server (using Effect-TS). There is a middleware (not in better-auth config), that needs to check 2 scenarios basically: 1. IF there is a session cookie, which needs to be validated (not idea how), THEN user is authenticated. 2. IF there isn't a session cookie, then we check Authorization: Bearer ${token} header and validate the JWT with JOSE lib. Questions 1. Do I need both bearer() and jwt() plugins enabled in better-auth config? 2. After user logged in / signed up on the server, will better-auth set a session cookie in headers automatically or do i have to extract it from somewhere and then set it myself? Where do i get this token from? Do I set the session token I received after logging in to the cookie? 3. What is generally considered a good practice for a middleware that checks the JTW with Bearer (for mobile and curl requests) and cookie token for web requests? Would greatly appreciate any answers and opinions.
17 Replies
FalconiZzare
FalconiZzare2w ago
2. If you are using axios, setting credentials: true will automatically send cookies. 3. See image below for a barebone setup of auth middleware:
No description
M
MOP2w ago
@FalconiZzare Thanks for your answer. As far as I know Effect-TS uses undici under the hood. At the moment I get this response data from my backend after signing up:
message: 'Signed Up',
userId: data.response.user.id
bearerToken: data.headers.get('set-auth-token') ?? '', // provided by bearer() plugin
sessionToken: data.response.token ?? '',
message: 'Signed Up',
userId: data.response.user.id
bearerToken: data.headers.get('set-auth-token') ?? '', // provided by bearer() plugin
sessionToken: data.response.token ?? '',
Then I take bearerToken and set it for Bearer Authentication and it works, when i call my protected by a middleware endpoint via curl , Postman or Swagger
auth.api.getSession({
query: {
disableCookieCache: true,
},
asResponse: false,
headers: fromNodeHeaders(headers), // as Bearer is there, it works
});
auth.api.getSession({
query: {
disableCookieCache: true,
},
asResponse: false,
headers: fromNodeHeaders(headers), // as Bearer is there, it works
});
However, I don't get 3 things: 1. Why when i set cookie: 'better-auth.session_token=my_session_token' manually in req headers, this auth.api.getSession() method fails? I wanted to test how my middleware will behave when only cookie is passed, without bearer token 2. Does Better-Auth set a cookie for me automatically only when using Better-Auth Client, not server API? 3. Would it be a good practice to implement a middleware for: - checking a set cookie (if a web browser client sending a request is authed) - when a mobile app / curl / postman makes a request (with bearer jwtToken, as cookie wont be set in this case) @FalconiZzare you here?
FalconiZzare
FalconiZzare2w ago
Hi, I'm not a TS expert. Also didn't combine bearer token with session. So I'm out of clue for your issue. Sorry didn't notice your reply earlier.
M
MOP2w ago
I see. Well, thanks anyway!
FalconiZzare
FalconiZzare2w ago
1. Umm... im not sure what you are trying to do, you need to pass everything from the cookie for the code I've shown you to work. It maps everything as in IP, userAgent, session token, csrf token etc. Try passing the whole cookie. 2. Better auth client automatically sets the cookie for you after a successful authn. 3. you can do 2 pass check. First check on the frontend for exitence of the cookie by following the NextJs middleware guide on better auth documentation, then do another check on server side but this time match everything. mobile/curl/postman can send request with cookies or using jwt, both. If you are only sending jwt then check jwt. Make a logic if no cookie is available, check for JWT, if none is available then deny the request. @M
M
MOP2w ago
I see, thanks! My Bearer auth in middleware works. I even grab JWT and compare it with JWT Keys from db. A user gets authed and i get a sub. (but thats only for mobile and curl) I want to test a cookies auth too, by setting it manually (thats for the web)
FalconiZzare
FalconiZzare2w ago
setting it manually where exactly? on the browser or on the request header?
M
MOP2w ago
in the header @FalconiZzare
curl --request POST \
--url http://localhost:8080/todos \
--header 'content-type: application/json' \
--cookie 'test.session_token=my_token_from_login' \
--data '{
"title": "Todo"
}'
curl --request POST \
--url http://localhost:8080/todos \
--header 'content-type: application/json' \
--cookie 'test.session_token=my_token_from_login' \
--data '{
"title": "Todo"
}'
FalconiZzare
FalconiZzare2w ago
You need to pass the whole cookie, not just the session token if you are using auth.api.getSession method to validate cookie.
FalconiZzare
FalconiZzare2w ago
FYI, this is the whole cookie, along with token, session, remember me etc.
No description
M
MOP2w ago
so where do i get that whole cookie from ?
FalconiZzare
FalconiZzare2w ago
Are you using Axios?
M
MOP2w ago
Nope
FalconiZzare
FalconiZzare2w ago
Well, I haven't figured out an efficient way to pass whole cookie into headers without axios, yet. However in axios config, just setting the property
credentials: true
credentials: true
does the trick for me. You can ask claude or ChatGPT for a way to include whole cookie object using your current setup.
M
MOP2w ago
Well, but this thing is that I just pass my headers here. The headers which I define in Swagger / curl
auth.api.getSession({
query: {
disableCookieCache: true,
},
asResponse: false,
headers: fromNodeHeaders(headers),
});
auth.api.getSession({
query: {
disableCookieCache: true,
},
asResponse: false,
headers: fromNodeHeaders(headers),
});
This getSession API is implemented on my backend middleware So I guess I have to grab that whole cookie from headers using Better Auth auth.api. signInEmail() API ? And then set it in headers using Swagger? Okay, i made it work finally. All good, my middleware works for both bearer and a cookie. Thanks for your help!
Julian
Julian4d ago
@M Are you using @effect/platform for your API?
M
MOP3d ago
@Julian Yeah

Did you find this page helpful?