简体   繁体   中英

What is client side and server side in Next.js?

Can anyone please explain me the concept of client side and server side in Next.js as they have mentioned in their documentation. What I know is that Next.js works on react which is client side and run in the browser and server side means the api (backend). Any help would be appreciated. Thanks

From Next.js documentation:

This function gets called at build time on server-side. It won't be called on client-side, so you can even do direct database queries. See the "Technical details" section.

 export async function getStaticProps() {
    
      const postsDirectory = path.join(process.cwd(), 'posts')
      const filenames = await fs.readdir(postsDirectory)
    
 }

I started writing NextJS app few months before, i'll explain as far as i know check whether it would be helpful.

Your understanding on client and server(API) is correct but in case of NextJS there is another client side and server side as NextJS is used for Server-Side Rendering(SSR).

In simple a same page Ex: pages/home.js when loaded with browser hard re-load https://example.com/home is loaded as server side. Pages written under /pages/ folder will be rendered server side on navigation. So the DOM elements of the page will be available in page source(view page source option in browser) which will be used by crawlers too.

You can find the difference by checking whether type of window,== 'undefined'. as window represents browser which is client and view page source of browser represents server side rendering.

In Pages also you can check

  1. Create a Next.js project

  2. Have two pages index.js and home.js

  3. In home.js write Home.getInitalProps method which is similar to useEffect or componentDidMount in react component. Here pages cannot contain componentDidMount or useEffect instead all API calls before render has to be done in getInitialProps or other related methods.

     Home.getInitialProps = async (context) => { const { req, query, res, asPath, pathname } = context if (.req) { if (typeof window.== 'undefined') { //its server side request happened on } } else { // its client side call that calls getInitialProps when routing happened Router.push('/home') from index page or inside components rendered from pages/index.js } }

Let me know if you need some more details, we can explore and figure it out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM