0

I am working on web application rendered via getServerSideProps in Next.js. In function getServerSideProps I set authorization token into header, but currently I am struggling how to get this token from header.

My code:

export async function getServerSideProps(ctx: NextPageContext) {
  const token: string = "Sample token"
  ctx.res?.setHeader("Authorization", token);

  return {
    props: {}
  }
}

const HomePage: NextPage<{}> = ({}) => {
  const token: string = "how to get token here?"

  return (
  )
}

export default HomePage

I am able to see the token in response via browser. enter image description here

Thanks for any advice!

1
  • Can you clarify what's the reason for setting an Authorization header inside getServerSideProps? Commented Jun 26, 2022 at 22:03

1 Answer 1

1

In getServerSideProps you return your token and in Homepage you get it by props

export async function getServerSideProps(ctx: NextPageContext) {
    const token: string = "Sample token"
    ctx.res?.setHeader("Authorization", token);
  
    return {
      props: {
        token
      }
    }
  }
  
  const HomePage: NextPage<{}> = ({ token }) => {
    console.log(token)
  
    return (
    )
  }
  
  export default HomePage
Sign up to request clarification or add additional context in comments.

4 Comments

Ahhh, in your solution token is stored in 2 places, in header and in body of response. I need it in the header for testing purposes. Maybe I am perfectionist, but is there a way to do it only via header?
i think you should store token in cookie, so it can be read in both server and client side
I guess so there is no better solution for this. Thanks.
cookies should never be read on client side to prevent XSS threats. httponly flag should always be set.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.