Next.js Auth Guard inside getServerSideProps

default discord avatar
Thinh Nguyen
9 months ago
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
    arielarial
    9 months 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 "/"

  • default discord avatar
    Thinh Nguyen
    9 months ago

    Thanks @arielarial for making this distinction clear!

  • discord user avatar
    jarrod_not_jared
    Payload Team
    9 months 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
    Payload Team
    9 months ago

    ^ @Thinh Nguyen what @jarrod_not_jared 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
    Thinh Nguyen
    9 months ago

    @jacobsfletch @jarrod_not_jared this is awesome, thank you 🙏

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.