Reputation: 3566
I have a custom _app.js
:
const Layout = ({ children }) => (children);
const app = ({ Component, pageProps }) => {
pageProps.baseUrl = 'some url';
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
};
And a page:
export async function getServerSideProps({ req, query, res, baseUrl }) {
// baseUrl is undefined and an error, if I am using it with destructiring
console.log(req) // There is no baseUrl
return { props: { ..... } }
}
I want to set that pageProps.baseUrl= 'some url';
in _app.js
and use it in page components including getServerSideProps
, how can I do that ?
Upvotes: 4
Views: 8174
Reputation: 3566
For now, I have created a file, which contains all global values like this:
let store = {};
const globalStore = {};
globalStore.set = (key, value) => {
store = { ...store, [key]: value };
}
globalStore.get = (key) => {
return store[key];
}
export default globalStore;
Then in _app.js
import it and set a value:
const app = ({ Component, pageProps }) => {
globalStore.set('baseUrl', 'some url 1');
globalStore.set('baseUrl2', 'some url 2');
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
}
import the file in pages/index.js
and inside the component or getServerSideProps
:
export async function getServerSideProps({ req, query, res }) {
console.log('in getServerSideProps');
console.log(globalStore.get('baseUrl'));
console.log(globalStore.get('baseUrl2'));
...
Upvotes: 3
Reputation: 426
I think, in this particular case, it's ok to use constants here instead of props.
In constants.js:
export const BASE_URL = 'some url';
And in your page:
import * as Constants from '../path/to/constants';
export async function getServerSideProps({ req, query, res }) {
// use Constants.BASE_URL here
return { props: { ..... } }
}
Your page component and the getServerSideProps method you export from the file are separate, and are executed at different times. Rendering your component does not call getServerSideProps. I believe the order in Next.js is like this:
pages/
for the corresponding routeIn this case, you have created a paradox. Think about how the props flow:
If getServerSideProps is responsible for creating the pageProps object, it can't also be passed that object as an argument.
Upvotes: 1