next.jsserver-side-renderingnext.js14

ways to test if code will be executed server or client-side


Learning NextJS / SSR in general, and I was wondering if there's a reliable way to check whether some part of my application will be run in the browser or on the server. The way NextJS 14 makes SSR + client components seamless by using the file system structure and exports with specific keyword names is really neat. I think I will eventually love it, but for now I'd appreciate some assurance that my server action function call really is being made on the server and isn't visible to my end users.

Is it just console.log and if you see it, then it must be client-side? Furthermore, is there a way to see logs/use a debugger for the server-side code?


Solution

  • Just add --inspect in script run NextJS: "NODE_OPTIONS='--inspect' next dev". See here.

    console.log can use to logging both server-side and client-side depend on where that show log. If log show in tab Console in Develops tool of your website, it is client code, but it show in terminal run NextJS or DevTools from chrome://inspect so it is server code. The simple way to detect server or client is check window object.

    if (typeof window == "undefined") {
      console.log("Application is on server side");
    } else {
      alert("Application is on client side");
    }
    

    When you use --inpsect you can use Chrome for debug server NextJS, just follow below steps:

    1. Run NextJS by this script "NODE_OPTIONS='--inspect' next dev", terminal will be show something like:
    Debugger listening on ws://127.0.0.1:9229/0cf90313-350d-4466-a748-cd60f4e47c95
    For help, see: https://nodejs.org/en/docs/inspector
    ready - started server on 0.0.0.0:3000, url: http://localhost:3000
    
    1. From Chrome, visit chrome://inspect for get tab debug NextJS server.
    2. Find Remote Target and click to inspect

    enter image description here

    And Debug Tab will be show like.

    enter image description here