简体   繁体   中英

Unable to set cookies from backend to frontend when deploying website

I'm using Nodejs for my server and Reactjs for my client. In my client, I use axios to perform post/get requests to the server. During development, everything is working perfectly fine, data is fetched and cookies are set properly. However, when I deploy my server and client to Heroku and Netlify respectively, the cookies are suddenly not set.

Here is my server code:


dotenv.config()
const server = express();
server.use(cors({origin: "https://frontendname.com", credentials: true}));

server.use(express.json());
server.use(express.urlencoded({extended:true}))
server.use(cookieParser())
server.use("/", fetchData)

server.listen(process.env.PORT, ()=>console.log(`Server listening on PORT ${process.env.PORT}`))
mongoose.connect(process.env.MONGO_URI, {useNewUrlParser: true, useUnifiedTopology: true}).then( () => {
    console.log("connected to mongoose")
    

}).catch((error) => console.log(error.message))

My server API code

res.status(201)       .cookie("accessToken", accessToken, {domain:"frontendwebsite.com", httpOnly: true, sameSite: 'strict', path: '/', expires: new Date(new Date().getTime() + 60 * 1000 * 4)})                          .cookie("refreshToken", refreshToken, {domain:"frontendwebsite.com", httpOnly: true, sameSite: 'strict', path: '/', expires: new Date(new Date().getTime() + 60 * 1000 * 96)})                          .json({message: "login verified", username: req.body.username})                 .send()

My client API code:

axios.defaults.withCredentials = true
export const loginAuth = async (credentials) => { 
    return await axios.post("https://backendname.herokuapp.com/loginAuth", credentials).then((res) => {
        
        return res
    })
}


I have a strong feeling its due to the domain name that is not correct in the "res.cookie". Since in my development when I'm using localhost for both server and client, it works. My client is hosted on Netlify and server is hosted on Heroku. My client has a custom domain name I got from GoDaddy. I used Netlify DNS on that domain name. Any ideas?

Can you inspect the response coming back from your server (with browser Dev Tools)? Is there any Set-Cookie header / value returning, or is it completely missing?

My guess is the cookie header is there, and being set, but with sameSite set to strict it won't send it to your backend / API. So I think you are right about the domain being incorrect, in res.cookie , you could try that with backendname.herokuapp.com . Since really you want the cookie to be transmitting to / from your backend, especially as it is httpOnly , it will never be used by your frontend / client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM