How do I detect I am on server vs client in Next.js

Now (2020 Jan) it should be typeof window === 'undefined' since process.browser is deprecated

Refer to https://github.com/zeit/next.js/issues/5354#issuecomment-520305040


You can use process.browser to distinguish between server environment (NodeJS) and client environment (browser).

process.browser is true on the client and undefined on the server.


Since I don't like depending on odd third party things for this behavior (even though process.browser seems to come from Webpack), I think the preferred way to check is for presence of appContext.ctx.req like this:

async getInitialProps (appContext) {

    if (appContext.ctx.req) // server? 
    {
        //server stuff
    }
    else {
        // client stuff
    }
}

Source: https://github.com/zeit/next.js/issues/2946

Tags:

Express

Nextjs