Reputation: 13
I've tried every work around, however, for some reason I keep getting the error in the screenshot below... not sure why?
Server Error
ReferenceError: window is not defined This error happened while generating the page. Any console logs will be displayed in the terminal window. Call Stack eval node_modules/gapi-script/gapiScript.js (1:9) ./node_modules/gapi-script/gapiScript.js file:[...]/.next/server/pages/[...]/[id].js (98:1) webpack_require file:/[...]/.next/server/webpack-runtime.js (33:42)
import { useEffect } from 'react';
import Head from 'next/head';
import styles from '../../../styles/Home.module.css';
import { GoogleLoginButton } from '../../../components';
import { gapi } from 'gapi-script';
export async function getServerSideProps(context: any) {
const res = await fetch(
`http://localhost:3000/api/...`,
);
const data = await res.json();
return { props: { data } };
}
const GAPI_CONFIG = {
apiKey: process.env.GOOGLE_API_KEY,
clientId: process.env.CLIENT_ID,
scope: process.env.GOOGLE_SCOPE,
};
export default function NblOneTeam({ data }: any) {
useEffect(() => {
function start() {
gapi.client.init(GAPI_CONFIG);
}
gapi.load('client:auth2', start);
});
return (
<div className={styles.container}>
<Head>
<title>NBL1 Scout Generator</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1>Hi NBL1 Teams</h1>
<GoogleLoginButton />
{data.map((player: any) => {
return <h2>{player.name}</h2>;
})}
</main>
</div>
);
}
As I mentioned, I've tried following work arounds like the following: Window is not defined in nextJS
Upvotes: 1
Views: 848
Reputation: 51
NextJs builds the pages server-side and window can only be accessed on the client-side. When the page loads window is always undefined in NextJs
The work around is importing gapi dynamically
useEffect(() => {
async function start() {
const gapi = (await import('gapi-script')).default
gapi.client.init(GAPI_CONFIG);
}
gapi.load('client:auth2', start);
}, []);
Upvotes: 2