Home / Article Detail

Next. js_Next.js: run the code server-side or client-side only in Next.js

📅 Oct 8, 2023✍️ lllomh
    next. js

    In your page components, you can execute code only in the server-side or on the client-side, but checking the window property.
    This property is only existing inside the browser, so you can check    
    if (typeof window === 'undefined') {

    }

    and add the server-side code in that block. 

    Similarly, you can execute client-side code only by checking   

    if (typeof window !== 'undefined') {

    }

    Alternatively, the following can be used to determine  _document.tsx  just run on the server

    if (!process.browser) { 

    console.log('This is running on the server.');

    } else {

    console.log('This is running in the browser.');

    }