Issue reliably getting cookies in API Routes.
How can I reliably get a cookie in the <script> part of one of my .vue files? It works if I click into the URL bar and hit enter, but not when I refresh or get redirected from an external webpage, or using a link inside of my app.
86 Replies
That is way too little information for anyone to help you. You haven't mentioned any packages, functions or shown any code
Exactly.
I am trying to use jsonwebtokens package to put my own token in a cookie. I realized the way I was doing it was not the best but it did work when I refreshed. Here is the code I used to have:
I since moved to using middleware, however, im still stuck on how to get the cookie in the middleware.
This is what I have for middleware code right now.
I did also try
but
getCookie
is undefined and using
gives me Cannot read properties of undefined (reading 'req')
So this code looks absolutely fine and the 'req' part tells me it might be an error in how you're fetching this endpoint
I have no idea what this could be doing as nowhere in the documentation do you set up request handlers or middleware like this, that's just a function https://nuxt.com/docs/guide/directory-structure/middleware
And what's wrong with the first block of code? That should work as long as you set the cookie correctly. And why are you comparing it to the query param?
Nuxt
middleware/ Ā· Nuxt Directory Structure
Nuxt provides middleware to run code before navigating to a particular route.
Comparing it to query param to check the state for oauth CSRF validation. The first block of code works perfectly fine ONLY when I click into the url bar and hit enter. Otherwise it gives me this error:
The error is because the cookie is undefined, unless I click into the url bar and hit enter.
I don't understand how that's even possible to get this error because you're doing
And somehow hitting this codeblock in jwt.verify
are you certain that's the code you're using and getting this error?
I guess I should clarify, if I remove the if statement I get that error, otherwise the cookie is just undefined and my logic fails anyways.
the exact code I used to get that error
oh this is peculiar
oh also hitting refresh does not work
hmm all this weird jankiness could be pointing to some odd browser quirk or the dev environment.
Another thought I have is that the cookie hasn't even been set by the time the component renders. Are you correctly setting the cookie in your api oauth callback and only then redirecting to the app?
Yes, cookie is set in the login page before the redirect to discord for oauth.
this does successfully set the cookie, I can see it even on the error page.
to be fair, I did have the same issue using the normal redirect for the login page. but putting external in the link fixed it.
Can you set cookies like that? Don't u need
setCookie
?only in middleware, the cookie setting works flawlessly. documentation gives this example:
in middleware this is the example, however I find it very lacking as the code provided does not work in the slightest for me, and there are no other examples.
wait
thats an api route sorry
give me a second, im going to try and convert this to an api route instead of a page.
LOL
API routes work
all I did was
inside of server/api/callback.ts
I should convert login to an api route as well. Thanks for troubleshooting with me though @Sandvich!
Glad you figured it out
š¤¦āāļø
Im at a loss. The cookie is undefined now, untill I hit enter in the url bar again.
Also login does not work with internal links, only external ones work.
I confirmed this issue is not browser specific, I tried it with edge, edge canary, and firefox.
I am still hitting this issue, would this be better addressed on github?
I am able to reproduce this issue with the default nuxt app only adding 2 files and the API folder.
only modified things is the API folder and callback.ts and login.ts
callback.ts
login.ts
github repo with the minimal reporoduction
https://github.com/Optio1/nuxtbugreproduction
GitHub
GitHub - Optio1/nuxtbugreproduction
Contribute to Optio1/nuxtbugreproduction development by creating an account on GitHub.
Also confirmed this still has problems after build.
But the clicking into url bar and hitting enter works in the build as well.
Just a thing to remember: If your cookie is httpOnly, you can't access it in js.
Even removing httpOnly I still have the same symptoms. HTTP only shouldnt matter in this case, because I need to get the cookie server side.
I did also try adding
if (process.client) return;
and wrapping the entire code in if (process.server) {}
.You're using useFetch or $fetch to get that endpoint?
neither, redirecting directly to it.
(Sorry, I did not read the full story)
thats alright, its a long one. Here is a video of the issue. I tried with pages, and api routes.
Il record another using the api routes
Wait a sec
for the recording, please open the chrome debug tools, to the network tab, filter for documents, preserve logs and show the request chain. Preferrably with some seconds between the requests so I can get some details through the compression. The interesting things are the request and response headers of each request.
will do
I can also just do this hold on
(replies might take a while, my pizza is about to ring the doorbell)
Oh, and the obvious question: Why not using nuxt-auth or similar? There is support for discord sso
I didint like the lack of documentation on how to use it, and its black boxy, ive built my own oauth halding before and just prefer to use that.
that's okay š
yeah, docs could be improved. It's basically just a wrapper for authjs, which actually works pretty well
ouh, that's nice!
am realizing thats mostly discord....
that's only discord š
yea its not capturing localhost
il grab a recording of the network tab
and more interesting: It has a request to that error reporting proxy. Might not be important though.
no delay in requests but I didnt see exactly where to do that
doesn't the inspector show any details?
like request headers?
yes
I'd really recommend using chromium/similar for that kind of debugging.
ive got edge if that has it
or I can install chrome
edge is fine
full disclosure im not very familar with chrome dev stuff
doesn't matter š I can setup an own test once I devoured those pizza slices
Does a .har file help you at all? I ran the site in edge with persist logs and downloaded them to an har file.
It should, yeah. Be aware, it may contain secrets, like cookies. Which is what we're interested in. Better share via dm.
not too woried, the cookie has a randomly generated state for my app and thats it.
alright, send it over
oh boy.
I need some minutes to jump through that
Just because im paranoied... I changed my discord password because thats the only other thing that I was authenticated with in edge.
š
It cant hurt you know š
True. Because I can see your discord jwt š
Figured that may be the case with the whole, routing to discord and authenticating for oauth thing.
Alright. I see the jwt, I also see an OPTIONS request to your callback.
I also see that options request as get request. Both return 500
At the end, I see your manual get request, with the same parameters. This one has a state-cookie.
Ah
so do I just need to enable cors
is that the whole problem
that could be
oh, your login page is actually setting that state cookie
yes
not cors, or atleast not that I would expect, I added the nuxt-security module which should by default add cors to everything.
I'm somehow missing the redirect from discord back to localhost
š¤·āāļø
maybe I should also note
this happens when setting the cookie as well
if I click a button in my nuxt app that redirects to the login page that is not expicitly tagged as external, it has the same error, but if I set it to external it works fine.
well, you'll have the same issue with useFetch and $fetch. They don't send the cookies.
I think that's why hard refreshing the page works
with fetch and useFetch you can do with credentials = true and then it sends the cookies
what? The docs show a more complex thing for that š
really?
Nuxt
Use Custom Fetch Composable Ā· Nuxt Examples
This example shows a convenient wrapper for the useFetch composable from nuxt. It allows you to customize the fetch request with default values and user authentication token.
I built myself an easier one:
had this issue with api calls and missing jwt
I tried this using the vue page script components as well, same problem. I mean, I can do something like that custom fetch with the plugins that just returns the token if thats going to work.
It just seems unnessesarily complex for something that seems like the current code should just work for.
I guess that's why nuxt-auth uses a session-endpoint to get its own data š
yea, il try the plugin way
if that yeilds the same results
IDK what to do
we're talking about client redirect, right?
ah, my brain... I wanted to ask if you tried attaching a debugger to see exactly what's happening...
whats weirder is the login api route when navigating to it renders a 404 error untill I click into it and hit enter, unless its an external link.
I can try attaching a debugger tomorrow here.
Ok so
it works if I set the link in the api route to redirect directly to the app
and skip discord
which for obvious reasons is not a solution
but it is progress
š¤¦āāļø š¤¦āāļø sameSite: lax fixes the cooke not appearing on discords redirect
still does not account for why I need an external link to get to /api/login or it returns 404 but thats alteast work arroundable
GitHub
Session data not available on external redirect to nuxt Ā· Issue #20...
Environment Operating System: Linux Node Version: v18.12.1 Nuxt Version: 3.4.2 Nitro Version: 2.3.3 Reproduction Unfortunately I'm not able to provide a reproduction, since it relies on externa...