I want to define a global array that I can set in getserverprops and use throughout the project. Is this possible in next js?
I'm going to use this array as a cache
getServerSideProps),
andIf you only ever want to access that variable inside getServerSideProps,
then that is theoretically possible, but likely will cause all sorts of problems. E.g. consider a load balancer and 3 different server instances,
which have 3 different caches.
Better would be to use some "established caching technology", like a Redis DB.
As said, you can not share a variable between server and client.
You might (as a mental model) consider getServerSideProps to be executed in a different country
on some secured server which you don't have access to, while the rest of the components (not all of them)
are executed on your computer in your browser.
So if you want to share some state between client and server, you need to create an API on the server, and communicate between client and server through this API.
If you just define a global array, that array will be created and can be used, but it will be created independently on the server and on the client, i.e. they will be two completely different variable.
my-app/global.js:
export const globalVariable = {
trace: [],
};
Then you access this variable inside the index.tsx:
my-app/pages/index.jsx:
const Home = ( props ) => {
console.log('Client: globalVariable', globalVariable);
console.log('Client: pageProps:', props);
useEffect(() => {
globalVariable.trace.push('from MyApp');
}, []);
return null;
}
export async function getServerSideProps() {
globalVariable.trace.push('from getServerSideProps');
return {
props: {
serverVariable: globalVariable,
},
}
}
Then you will have one globalVariable on the client, and a separate globalVariable on the server.
You will never see "from getServerSideProps" on the client, you will never see "from MyApp" on the server.
You can pass globalVariable from the server as props, like I did with serverVariable: globalVariable,
and that value will be available on the client, but it will be a third new variable on the client side.
You can not hope to props.serverVariable.trace.push('pushed from client to server'), that will only push
to the new client variable.