In your custom app file _app.js
:
import Cookies from "cookies";
import { v4 as uuidv4 } from "uuid";
function MyApp({ Component, pageProps }) {
return (...)
}
MyApp.getInitialProps = async (appContext) => {
const appProps = await App.getInitialProps(appContext);
const { req, res } = appContext.ctx;
const cookies = new Cookies(req, res);
let playerId = cookies.get("playerId");
if (!playerId) {
playerId = uuidv4();
cookies.set("playerId", playerId);
}
return { ...appProps, playerId };
};
export default MyApp;