'How to convert getInitialPropsTo getServerSideProps?
I have this function in my next js app , in _app.js file. I want to convert it in getServerSidePops function but I get errors whatever I try.
App.getInitialProps = async (props) => {
const { Component, ctx, router } = props
let apiClient = typeof window !== 'undefined' ? getApiClient() : null
let cmsProps = {}
// In case `getInitialProps` here fails, Next.js will call this method again
// with `./_error.js` as `Component` and the stack trace as context.
if (Component.displayName === Error.displayName) {
const pageProps = await Component.getInitialProps(ctx)
return {
cmsProps: {},
pageProps: {
...pageProps,
page: {
...pageProps.page,
disableAppBase: true,
},
},
status: pageProps.statusCode,
}
}
const pageProps = {}
try {
if (ctx.req) {
const cookies = new Cookies(ctx.req, ctx.res, {
secure: process.env.NODE_ENV === 'production',
})
apiClient = new ApiClient(cookies)
cmsProps = await fetchGlobalSettings(ctx)
}
let url
apiClient.readCookies()
const domain =
process.env.NODE_ENV === 'production'
? publicRuntimeConfig.TINYLINK_PREFIX
: 'http://localhost:3000'
const market = router.locale !== `redirect` && router.locale
const marketAsPath = market ? `/${router.locale}` : ``
const selectedMarket = apiClient.selectedMarket
const selectedMarketAsPath = selectedMarket ? `/${selectedMarket}` : ``
const origUrl = `${domain}${marketAsPath}${ctx.asPath.split('?')[0]}`.replace(/\/$/, '')
const routingOpts = {
url: `${domain}${marketAsPath}${ctx.asPath.split('?')[0]}`.replace(/\/$/, ''),
urlLanguage: false,
routing: true,
}
if (ctx.req) {
routingOpts.ipAddress = ctx.req?.headers?.['x-real-ip'] || ''
}
const appInit = async (opts) => {
const init = await apiClient.init(opts)
if (init.url) {
url = init.url
}
}
if (!apiClient.sessionToken) {
await appInit(routingOpts)
} else {
try {
let decoded
if (router.locale === 'redirect' && selectedMarket) {
decoded = await apiClient.decodeShortLink({
...routingOpts,
routing: false,
url: `${domain}${selectedMarketAsPath}${ctx.asPath.split('?')[0]}`.replace(/\/$/, ''),
})
} else {
decoded = await apiClient.decodeShortLink(routingOpts)
}
url = decoded.url
} catch (error) {
// If token error reinitialise app
await appInit(routingOpts)
}
}
if (apiClient?.cookies) {
apiClient?.cookies.set('MARKET', router.locale === 'redirect' ? 'eu' : router.locale, {
httpOnly: false,
secure: process.env.NODE_ENV === 'production',
domain: publicRuntimeConfig.COOKIE_DOMAIN,
sameSite: publicRuntimeConfig.COOKIE_SAMESITE,
})
}
if (url && url !== origUrl) {
if (ctx.asPath.indexOf('?') !== -1) {
url = `${url}?${ctx.asPath?.split('?', 2)[1]}`
}
if (ctx.res) {
// On the server, we'll use an HTTP response to
// redirect with the status code of our choice.
// 307 is for temporary redirects.
ctx.res.writeHead(307, { Location: url })
ctx.res.end()
} else {
// On the client, we'll use the Router-object
// from the 'next/router' module.
router.replace(url)
}
// Return an empty object,
// otherwise Next.js will throw an error
return { redirect: true }
}
cmsProps.hello = await apiClient.hello()
cmsProps.products = formatProducts(cmsProps?.hello?.products)
cmsProps.translations = formatTranslations(cmsProps?.hello?.translations)
} catch (error) {
console.error('error', error)
}
return {
cmsProps,
pageProps,
}
}
Convert this function to getServerSideProps function.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
