Nathaz
Nathaz

Reputation: 53

How to get header from SSR response in Next.js

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!

Upvotes: 0

Views: 2593

Answers (1)

iamhuynq
iamhuynq

Reputation: 5539

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

Upvotes: 1

Related Questions