Like what we’re doing? Star us on GitHub!

Next.js Auth Guard inside getServerSideProps

Thinh Nguyen
2 weeks ago
6

Started using Payload with Next.js and i'm interested in implementing an auth guard during SSR that makes a request to the

/api/users/me

endpoint from within

getServerSideProps

to verify if the user is authenticated or else they will get redirected.



Would something like this work?



export async function getServerSideProps(context: GetServerSidePropsContext) {
  const res = await fetch("http://localhost:8080/api/users/me", {
    credentials: "include",
  });
  const { user, errors } = await res.json();

  if (!user) {
    return {
      redirect: {
        destination: "/",
        permanent: false,
      },
    };
  }

  return {
    props: {
      user: user,
    },
  };
}
  • arielarial
    2 weeks ago

    Hi @Thinh Nguyen ! I don't think any kind of SSR will work for this, because this code won't run in the user's browser. It will run in the server, so the authentication cookies will not be present to be validated. Therefore, your code will always return a redirect to "/"

  • Thinh Nguyen
    2 weeks ago

    Thanks @arielarial for making this distinction clear!

  • Jarrod
    Payload Team
    2 weeks ago

    I know in the app folder you can get the cookies off the request, and then you can make that same

    /me

    fetch with:



    // you will need to get cookies from req (Context?) and then look for the payload-token cookie
    
    fetch("http://localhost:8080/api/users/me", {
      headers: {
        Authorization: `JWT ${jwt from cookie on req}`,
      }
    }
  • jacobsfletch
    Payload Team
    2 weeks ago

    ^ @Thinh Nguyen what @Jarrod describes is the right pattern here. You just need to manually inject the token into the

    Authorization

    header within your server-side request. There's a demonstration of this in our official preview example, check it out

    https://github.com/payloadcms/payload/blob/master/examples/preview/nextjs/pages/%5Bslug%5D.tsx#L74

    . It uses

    getStaticProps

    but the same principle applies.

  • Thinh Nguyen
    2 weeks ago

    @jacobsfletch @Jarrod this is awesome, thank you 🙏

Open the post
Continue the discussion in Discord
Can't find what you're looking for?
Get help straight from the Payload team with an Enterprise License.Learn More