hoangvvo / next-connect

The TypeScript-ready, minimal router and middleware layer for Next.js, Micro, Vercel, or Node.js http/http2
https://www.npmjs.com/package/next-connect
MIT License
1.64k stars 65 forks source link

How can I set cookies on the response, and then redirect? #168

Closed lumenwrites closed 2 years ago

lumenwrites commented 2 years ago

Hi there! I'm new to next-connect, I've been stuck on this issue for awhile, and I'm really hoping you could help me out.

I'm trying to implement Twitter auth in my app, and at the end of the process my user lands on one of my api urls, where I have all the data relevant to the auth. My goal is to save the auth token I have generated into cookies, and then redirect the user back to my app, something like this:

      const token = jwt.encode({ twitterUserId: user.twitterUserId }, process.env.JWT_SECRET)
      res.cookie('token', token, { maxAge: 99999999999999 })
      res.redirect('/')

But this doesn't work, it gives me a TypeError: res.cookie is not a function.

Can you please help me to figure out how to solve this?

hoangvvo commented 2 years ago

res.cookie is not defined in Next.js. See https://nextjs.org/docs/api-routes/api-middlewares#extending-the-reqres-objects-with-typescript for how to set cookie.