Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Next.js Auth Guard inside getServerSideProps

default discord avatar
giaguunslast year
5

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,
    },
  };
}
  • default discord avatar
    arielarial2 years ago

    Hi

    @520438276964876298

    ! 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 "/"

  • default discord avatar
    giaguuns2 years ago

    Thanks

    @736673642158620680

    for making this distinction clear!

  • discord user avatar
    jarrod_not_jared
    2 years 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}`,
      }
    }
  • discord user avatar
    jacobsfletch
    2 years ago

    ^

    @520438276964876298

    what

    @281120856527077378

    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/draft-preview/next-pages/src/pages/%5Bslug%5D.tsx#L74

    . It uses

    getStaticProps

    but the same principle applies.

  • default discord avatar
    giaguuns2 years ago
    @808734492645785600

    @281120856527077378

    this is awesome, thank you 🙏

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.