The next. Js server rendering framework is a real lifesaver. I had been looking for the React server rendering framework and had no satisfactory answer until I came across next.js.

So how is next. Js different from standard React.Com Ponent?

Reading the code, I found that next. Js has a function to initialize props.

// file: lib/utils.js
export async function loadGetInitialProps (Component, ctx) {
  if(! Component.getInitialProps)return {}

  const props = await Component.getInitialProps(ctx)
  if(! props && (! ctx.res || ! ctx.res.finished)) {const compName = Component.displayName || Component.name
    const message = `"${compName}.getInitialProps()" should resolve to an object. But found "${props}" instead.`
    throw new Error(message)
  }
  return props
}Copy the code

Next. Use js Component. GetInitialProps to initialize components. Component. GetInitialProps is marked as asynchronous function (await), therefore returns a Promise or async tag function. This also provides guarantees for loading asynchronous data.

The parameters of the Component. GetInitialProps CTX, the browser client and server side is not the same, still found through code.

// file: server/render.js#L52
const ctx = { err, req, res, pathname, query }Copy the code
// file: client/index.js#L102
props = await loadGetInitialProps(Component, { err, pathname, query })Copy the code

{req, res}, req is the server Request object, res is the server Response. You can do a lot of things with these two things.

Of course, next. Js as a framework does a lot more than that, and there are some amazing things you need to know more about when you use it.