Next.js and SSR Authentication Content

2022-06-18

Authentication is an issue that can have many different approaches when it comes to implementation. One of the most common implementations is using sessions, where user data and log in sessions are stored entirely on the server. The client - the user themselves - only has the session id, which is stored in a cookie on their browser. With every request sent by the client to the server, the cookie is attached, and the server can use that cookie to authenticate the user.

When it comes to SSR, this pattern of authentication becomes a bit more complex when you want to have authenticated content server side rendered. Let's assume we have an endpoint like '/api/polls'. This endpoint serves a list of polls and if the user is authenticated, each poll will have the users voting status. To display these polls, a page in Next.js calls the function below to server side render the information.


export const getServerSideProps: GetServerSideProps = async () => {
  const res = await axios('/api/polls')
    return {
        props: {
            polls: res.data
        }
    };
};

const HomePage = ({polls}) => {
  return (
    
{polls.map(poll => (
{poll.title}
)}
) }

Now let's assume that a user has logged in and has a session cookie in their browser. If they were to visit this page, the polls would be prerendered but their vote status is missing! This is because the request sent by getServerSideProps() does not have the cookie from the user request. In this case, we need to forward the cookie from the user request to the axios call in getServerSideProps().


export const getServerSideProps: GetServerSideProps = async ({ req }) => {
  // forward the cookie!
  axios.defaults.headers.get.Cookie = req.headers.cookie;
  const res = await axios('/api/polls')
    return {
        props: {
            polls: res.data
        }
    };
};

And now the end point in '/api/polls' should have access to the user session cookie, be able to get the user data and check their vote statuses on the polls.