Home > Mobile >  Handling auth inside getStaticProps requests
Handling auth inside getStaticProps requests

Time:04-29

I have a NextJs application with its back-end in Laravel.

All of our Laravel api routes are protected with Laravel Sanctum to prevent XSS attacks.

The problem is that this auth method relies on sending cookies with each request. So when I try to make these requests from getStaticProps function, I do not have cookies available.

What is best practice for this scenario? Disable sanctum for the specific routes needed in getStaticProps? Or is there some black magic that will help me retrieve the needed cookies?

CodePudding user response:

This is a toughie! Unfortunately it is a bit of an anti-pattern to have auth locked content and static content in the same conversation because static data usually shouldn't depend on dynamic data if that makes any sense. You might be able to find some more information here in case it's helpful however: Next.js withPageAuthRequired with getStaticProps.

CodePudding user response:

getStaticProps() is run during the build time and just once unless you use revalidate and set it to number of seconds, and also it does not have access to the (req,res). The next.js built-in function that runs on every upcoming request sent to the server in order to generate the page, is getServerSideProps().

  export default async function getServerSideProps(context){
   //some code here.... 
   return {
    props:{data}
   }
  }
  • Related