I am trying to fetch data server side first time if a page is reloaded. For this, I am using getInitialProps in page to get the data. Here is the code that I am trying
Student.getInitialProps = async (ctx) => {
try {
const response = await axios({
method: "get",
url: `http://localhost:3333/teacher/student/getAllStudent`,
headers: ctx?.req?.headers?.cookie ? { cookie: ctx.req.headers.cookie } : undefined,
withCredentials: true,
})
console.log("my reso",response.data)
return { data: response.data }
} catch (error) {
if (ctx.res) {
console.log(error.message)
ctx.res.writeHead(302, {
Location: "/",
})
ctx.res.end()
}
}
}
this code works perfectly, but I would like to use a function to avoid writing same code/config again and again. Here headers, full url etc all are repeating every pages. How can I write it somewhere and use it from all pages?
Thank you.