H
Hono4w ago
Lambo

Cookie Comes Back As undefined

Hello. I'm using Hono and having an issue setting a cookie on one endpoint and retrieving it in the middleware of another. I was wondering if someone could advise as to why it comes back undefined. Thanks!
authRouter.get('callback', async (c) => {
// irelevant logic...
console.log(data.access_token); // has value

setCookie(c, 'auth', data.access_token, {
path: '/',
secure: true,
domain: new URL(c.req.url).hostname,
httpOnly: true,
maxAge: 1000,
expires: new Date(new Date().getTime() + (data.expires_in * 1000)),
sameSite: 'strict'
});

return c.json({ success: true });
});
authRouter.get('callback', async (c) => {
// irelevant logic...
console.log(data.access_token); // has value

setCookie(c, 'auth', data.access_token, {
path: '/',
secure: true,
domain: new URL(c.req.url).hostname,
httpOnly: true,
maxAge: 1000,
expires: new Date(new Date().getTime() + (data.expires_in * 1000)),
sameSite: 'strict'
});

return c.json({ success: true });
});
export const verifyTokenMiddleware = createMiddleware(async (c, next) => {
const token = getCookie(c, 'auth');

console.log('got token', { token }); // undefined

return next();
});
export const verifyTokenMiddleware = createMiddleware(async (c, next) => {
const token = getCookie(c, 'auth');

console.log('got token', { token }); // undefined

return next();
});
I am also open to alternate options for passing around auth tokens.
17 Replies
Lambo
LamboOP4w ago
I don’t follow?
ambergristle
ambergristle4w ago
hey @Lambo! a few small tweaks might be helplful, though they probably won't fix: - domain: instead of pulling dynamically from Request, this should be hard-coded (e.g., in your .env variables) to a deployment - secure: this should only be true in production, e.g., secure: process.env.NODE_ENV === 'production' (unless you're running https locally, but still) - expires and maxAge accomplish the same goal, but maxAge is newer + more resilient. just use that, instead of both actually, now that i think about it, secure is probably your problem everything else seems legit except for this bit: authRouter.get('callback',
Nico
Nico4w ago
Ignore that was from my pocket
ambergristle
ambergristle4w ago
@Lambo i assume you've verified that the cookie is set/available on the client
Lambo
LamboOP4w ago
Hey, thanks for the response (and no worries about the pocket typing haha). I am in bed now but I will give those amends a go tomorrow. I could not see the cookie set on the client, but assumed maybe it was because it was secure or something, but your explanation makes sense. I’m using Workers Pages Functions locally if it’s of any reference
ambergristle
ambergristle4w ago
happy to help! if you can't see the cookie in your browser, that's probably a red flag http-only cookies can't be interacted w using client-side js, but they should still show up in the inspector one thing you could try: after you set the cookie, in the same handler/middleware, log out c.header() or whatever, and take a look at the cookie header that will confirm whether it's being set at all, and give you a better sense of whether any values look funky (but domain and/or secure seem to be the most likely culprits, atm)
Lambo
LamboOP4w ago
Hey @ambergristle - still no luck, unfortunately. 1. I changed secure to c.env.WORKER_ENV === 'prod' 2. Tried setting domain to http://localhost:8788, localhost:8788 and localhost 3. Removed expires All of these log undefined:
const x = getCookie(c, 'auth');

console.log(c.header('Cookie'));
console.log(c.header('Set-Cookie'));
console.log(x);
const x = getCookie(c, 'auth');

console.log(c.header('Cookie'));
console.log(c.header('Set-Cookie'));
console.log(x);
...and I see nothing in the browser suggesting a cookie is set either Any other pointers you may have?
ambergristle
ambergristle4w ago
hmmm you're doing those logs in the same handler/middleware that's supposed to set the cookie? this isn't the actual path/endpoint, right? authRouter.get('callback', ...) i might try dropping sameSite to Lax without knowing more about your setup, my next play would be to start w a vanilla cookie (just key/value, no settings) and see if that gets set then start adding things back in until it breaks (unless it didn't get set, in which case you know your config isn't the issue)\ @Lambo do you have cors set up?
Lambo
LamboOP4w ago
Yeah. So I have GET /auth/callback which sets the cookie. No CORS setup I can have a play around in a few hours after work
ambergristle
ambergristle4w ago
try adding the hono cors middleware, shouldn't need to config
ambergristle
ambergristle4w ago
Stack Overflow
Response Set-Cookie not working, but only on Cloudflare Pages/Workers
I am working on a simple app with Auth.js and Next.js. In specific, I am using it with WebAuthn authentication. So, I have a pretty similar auth.ts setup: export const { handlers, signIn, signOut, ...
ambergristle
ambergristle4w ago
oh, one of the reasons the first two are logging undefined is that you actually want c.req.header('cookie') c.header is a setter only, not a getter
Lambo
LamboOP4w ago
No different with lax or CORS or not setting any options Oh wait, I had to remove the c.header() as that just overwrite. Getting a result now Cool, let me start adding things back Looks like sameSite: 'strict' was doing it. lax is fine Thank you so much, finally unblocked!
ambergristle
ambergristle4w ago
let's gooooo i've found the lucia auth docs really helpful (though they're still sort of WIP)
ambergristle
ambergristle4w ago
Lucia
Session cookies
An open source resource on implementing authentication with JavaScript
ambergristle
ambergristle4w ago
(and the Copenhagen Book it's based on) i'm new to building auth, and they've helped contextualize all the different bits
Lambo
LamboOP4w ago
That’s great, I’ll give it a read. Thanks for the recommendation

Did you find this page helpful?