Home > OS >  Nextjs - I can't get request an api which depends on backend cookie
Nextjs - I can't get request an api which depends on backend cookie

Time:08-17

1: here I generate refreshtoken when logging in and I generate cookie using 'cookie-parser' and send the cookie to the path '/user/refresh-token'

res.cookie('refreshtoken', refreshtoken, {
        httpOnly: true,
        path: '/user/refresh-token',
        maxAge: 1000 * 60 * 60 * 24 * 7,
      });

2: here I try to fetch the cookie I sent to this path 'user/refresh-token' but it's always sending err 400 which means that it can't read the cookie I sent here. I tried the api on postman and it's working fine and I can see the cookie, I just can't fetch this api route on the client after logging in

refreshToken: async (req, res) => {
    try {
      const refreshtoken = req.cookies.refreshtoken;
      if (!refreshtoken) {
        return res
          .status(400)
          .json({ msg: "not authenticated, signup or login" });
      }

3: and here is the code for the client side using createContext

export const DataProvider = ({children}) => {
    const [token, setToken] = useState(false)

     useEffect(()=> {
        const firstLogin = localStorage.getItem('firstLogin')
        if(firstLogin){
            const refreshToken = async ()=>{
                const res = await fetch('http://localhost:8000/user/refresh-token')
                await res.json();
            }
            refreshToken()
         }
     }, [])

5: so in conclusion when the user log in it generates a cookie and save it to the path '/user/refresh-token', and then I create item called 'firstLogin' and store it in local storage to be a mark that the user is logged, and it directs me to the '/' page using 'window.location.href', and then the function in the context get this item and start to fetch the api which the cookie exist in and it results in error 400 that there is no cookies sent.

CodePudding user response:

fetch won't send cookies for cross-origin requests unless you set the credentials option to true.

const options = { credentials: true };
const res = await fetch('http://localhost:8000/user/refresh-token', options)

Note that this will make the request preflighted so you may have to adjust the CORS configuration of the server.

  • Related