Next.js

A new approach to universal javascript app

Garry Yao

An ideal Next component is just one page, you don't even need a server.js

In reality you'll need a server (example in Express)  

Most of the time you'd like to split page render with api as well. 

A universal component most of time is asymmetrical - isomorphic is not as simple as it's said 

Meet Next's getInitialProps

  • pathname - path section of URL

  • query - query string section as an object
  • asPath - actual path (including the query) shows in the browser
  • req - HTTP request object (server only)
  • res - HTTP response object (server only)
  • jsonPageRes - Fetch Response object (client only)
  • err - Error object if any error is encountered during the rendering

async static method that populates props 

Since we have page, we need to move between pages - so you have <Link>

For sure we'll need to pass data to the next page, so that makes a query

How <Link> works

  1. The component is fetched
  2. getInitialProps get called with path and query from link's href 
  3. If an error occurs, _error.js is rendered
  4. pushState/replaceState is performed
  5. The new component is rendered

Since <Link>'s href is to bridge with getInitialProps, we may need another real page url (for human, browser and server)
 

<Link href="/blog?id=1" as="/blog/1">

Have you ever think about prefetching a link? This shall be just one attribute away -
Think of <link rel=“prefetch”>

When our JavaScript component is universal, people start to think what does universal mean for css, which leads to...

styled-jsx use unique classname for style encapsulation and optimization on the server - all boil down to inline css 

Ofc, if you're not a big fan of styled-jsx (like me), there's definitely a way out - 

 

Webpack-based css loaders are available as next plugins:

 

  • next-css

  • next-less

  • next-sass

Webpack is pre-configured for next, config be called once for the client and once for the server.

You can even make universal env variables!

 

- use a universal config module

- use _document override to ship env to the client

Few limitations I run into with Next

No built-in support for server code in ES6, you'll need babel for server code configured in a different env

Override the built-in webpack config wasn't easy...

Not a perfect framework but promising, expecting more to come in Next!

Q&A

Made with Slides.com