Search code examples
next.jsserver-side-renderingnext-auth

Next.js Build fails. window is not defined


I'm building a next.js app and it works perfect in development mode. While deploying to production it fails with the following error:

[    ] info  - Generating static pages (0/6)/home/ec2-user/groot-dashboard/node_modules/next-auth/react/index.js:220
            _ref5 = options !== null && options !== void 0 ? options : {}, _ref5$callbackUrl = _ref5.callbackUrl, callbackUrl = _ref5$callbackUrl === void 0 ? window.location.href : _ref5$callbackUrl, _ref5$redirect = _ref5.redirect, redirect = _ref5$redirect === void 0 ? true : _ref5$redirect;
                                                                                                                                                               ^

ReferenceError: window is not defined
    at _callee5$ (/home/ec2-user/groot-dashboard/node_modules/next-auth/react/index.js:220:160)
    at tryCatch (/home/ec2-user/groot-dashboard/node_modules/@babel/runtime/helpers/regeneratorRuntime.js:86:17)
    at Generator._invoke (/home/ec2-user/groot-dashboard/node_modules/@babel/runtime/helpers/regeneratorRuntime.js:66:24)
    at Generator.next (/home/ec2-user/groot-dashboard/node_modules/@babel/runtime/helpers/regeneratorRuntime.js:117:21)
    at asyncGeneratorStep (/home/ec2-user/groot-dashboard/node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:24)
    at _next (/home/ec2-user/groot-dashboard/node_modules/@babel/runtime/helpers/asyncToGenerator.js:25:9)
    at /home/ec2-user/groot-dashboard/node_modules/@babel/runtime/helpers/asyncToGenerator.js:32:7
    at new Promise (<anonymous>)
    at /home/ec2-user/groot-dashboard/node_modules/@babel/runtime/helpers/asyncToGenerator.js:21:12
    at _signIn (/home/ec2-user/groot-dashboard/node_modules/next-auth/react/index.js:329:18)
[=   ] info  - Generating static pages (0/6)/home/ec2-user/groot-dashboard/node_modules/next-auth/react/index.js:220
            _ref5 = options !== null && options !== void 0 ? options : {}, _ref5$callbackUrl = _ref5.callbackUrl, callbackUrl = _ref5$callbackUrl === void 0 ? window.location.href : _ref5$callbackUrl, _ref5$redirect = _ref5.redirect, redirect = _ref5$redirect === void 0 ? true : _ref5$redirect;

What should i do? Can't understand anything..


Solution

  • It is very hard to help you when you are not showing the code that causes the error ...

    When I guess I think you are using window.* in your code and this is not available at build time so one way is to check if it is existing with

    if (typeof window == 'undefined') {
         // Client-side-only code
    }
    

    or use the useEffect hook

    useEffect(() => {
        // Client-side-only code
    })
    

    If you provide some parts of your code more specific help is possible :)