Can I set custom cookies when successfully logged in? #4428
-
Question 💬Hi, I've been using Next-Auth CredentialsProvider, I want to set some custom cookies when logged in, but it didn't work. Login works perfectly but it doesn't set custom cookies. My Next-Auth version is How to reproduce ☕️export default (req, res) => {
return NextAuth(req, res, {
providers: [
CredentialsProvider({
name: "creds",
credentials: {
username: { label: "Username", type: "text", autoComlete: 'off' },
password: { label: "Password", type: "password" }
},
async authorize(credentials) {
const user = await login(credentials);
if ( user ) {
res.setHeader('Set-Cookie', 'my_cookie=value');
return user;
}
throw new Error("Invalid creds");
},
}),
], Contributing 🙌🏽Yes, I am willing to help answer this question in a PR |
Beta Was this translation helpful? Give feedback.
Replies: 8 comments 18 replies
-
I don't think there is an API for setting custom cookies in NextAuth.js atm 🤔 cc @balazsorban44. Setting cookies in the |
Beta Was this translation helpful? Give feedback.
-
I would like to hear the use case for this. |
Beta Was this translation helpful? Give feedback.
-
Hi Guys, The package import { setCookie } from 'nookies';
async authorize(credentials){
//...
setCookie({ res }, 'name', 'value',{
maxAge: 2 * 24 * 60 * 60,
path: '/',
httpOnly: true
})
} |
Beta Was this translation helpful? Give feedback.
-
@DoronTorangy were you or anyone else able to find a solution for nextjs 13? |
Beta Was this translation helpful? Give feedback.
-
If anyone using route handler you can set cookies using 'coookies' from next/headers as below:
you can read more about it here: app router cookies |
Beta Was this translation helpful? Give feedback.
-
app/api/auth/[...nextauth]/route.ts import { cookies } from 'next/headers'; cookies().set({ |
Beta Was this translation helpful? Give feedback.
-
guys have you manage to create interceptor and set this cookie for header, like i have some progress but then problem comes that some requests are client other are server and cnat use cookies :@ |
Beta Was this translation helpful? Give feedback.
-
I think it worked with credentialProvider but how can we set cookie with an oauth like google |
Beta Was this translation helpful? Give feedback.
That works, if you are having problems with TypeScript types, simply change [...nextauth].ts file to [...nextauth].js.
Example working code that saves cookies: