I am using Nextjs with next-auth for authentication with node.js at the backend . Now , I am setting my cookies in node.js and it works correctly in postman. I can authenticate ,without any issue. When it comes to NextJs , since I am only returning the res.data
from the response , which essentially contains the user data and not JWT , I am not able to pass the cookies to the frontend. Hence, I am not authenticated for Node.js .I checked the documentation for cookies on next-auth but couldn't make it work .
The code for ./api/[...nextauth.ts]
import axios from 'axios'
import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
export default NextAuth({
// Configure one or more authentication providers
providers: [
Providers.Credentials({
name: 'Credentials',
credentials: {
email: { label: "Email", type: "email", placeholder: "Your email" },
password: { label: "Password", type: "password",placeholder: "*********" }
},
async authorize(credentials:any, req) {
try
{
const res = await axios.post('http://node-app:4200/users/login',credentials)
if(res.status==200)
{
return res.data
}
}
catch(e:any){
console.log(e.data)
}
return null
}
})
],
pages: {
signIn: '/auth/login',
signOut: '/auth/logout',
// error: '/auth/error', // Error code passed in query string as ?error=
// verifyRequest: '/auth/verify-request', // (used for check email message)
// newUser: undefined // If set, new users will be directed here on first sign in
}
})
It would be helpful if someone could guide me how to add the cookies that I pushed from node.js to the nextjs's server side can be pushed to the next's frontend.
axios
throws an error for any status code outside 200-299, so you don't have to do theres.status === 200
check toreturn res.data
:) – Middle