javascriptreactjscookiesnext.jsreact-cookie

How to include cookies with fetch request in Nextjs


Consider the following code

Index.getInitialProps = async function({req}) {
  const res = await fetch("http://localhost/api/tiles");
  const json = await res.json();
}

Suppose the /api/tiles endpoint needs access to the uid cookie on the user. Normally, one would do {credentials: "include"}. But how do I do this in Next.js?


Solution

  • As you are using React (NextJS is built on ReactJS) you can use react-cookie to get and cookies that are stored in the system.

    Install react-cookie

    npm install react-cookie
    

    If you are using Reactjs with version >= 16.8.0 you can use React hooks.

    const [cookies, setCookie, removeCookie] = useCookies(['cookie-name']);
    

    You can set cookie with setCookie(name, value, [options]) and get the cookies with cookie.get(name, [options])

    So in your case the code should look like

    import { useCookies } from 'react-cookie';
    const [cookies, setCookie] = useCookies(['name']);
    
    Index.getInitialProps = async functon({req}) {
      cookie = cookies.get(name)
      const res = await fetch("http://localhost/api/tiles", cookie);
      const json = await res.json();
    }