0

I don't understand a bit how to make such a video correctly.

The cookie stores data, and when entering the page, it should be checked for access

/page/post.ts/

import CheckToken from '../../../utils/CheckToken';

export async function getServerSideProps(context) {
    CheckToken(context.req, context.res);
    return {
      props: {
        tabledb,setting
        }, // will be passed to the page component as props
    }
  }

 export default function post() {
  
   return ()  
   }

..../../../utils/CheckToken

export default async function handler(req,res) {
  try {
...//Data
  } catch(err) {
    res.redirect(401,"/admin/login" )
  }
}

If it fails or if there is an error, I need to redirect to the authorization page But res.redirect doesn't work outside of the api. Tell me then how to make a check then?

config314
  • 49
  • 7

1 Answers1

1

Your CheckToken function should return some kind of result to indicate if the call was successful or not, then based on that you can do a redirect.

export async function getServerSideProps(context) {
    const result = CheckToken(context.req, context.res);
    
    // if "falsy" do the redirect
    if (!result) {
      return {
        redirect: {
          destination: '/signin',
          permanent: false,
        },
      }
    }

    return {
      props: {
        tabledb,setting
        }, // will be passed to the page component as props
    }
  }
Ivan V.
  • 7,593
  • 2
  • 36
  • 53
  • It just seems to me that a lot of the same type of code will be written to check the token, is there really no other option? And if there are 50 pages, then there will be a lot of repetition of the same type. – config314 Aug 27 '21 at 13:24
  • @config314 You can abstract the logic to a higher-order function and reuse it on all the pages that require it, as described in [Creating a HOC (higher order component) for cookies in nextJS](https://stackoverflow.com/a/66088247/1870780). – juliomalves Aug 28 '21 at 10:09