Next.js
The React Framework for Production
Agenda
-
History
-
Yet another architecture
-
Next.JS functionality
Created by Vercel
Vercel is a cloud platform for static sites and Serverless Functions...
It enables developers to host Jamstack websites ...
What is the Jamstack?
"A modern web development architecture based on client-side JavaScript, reusable APIs, and prebuilt Markup"
— Mathias Biilmann (CEO & Co-founder of Netlify).

client-side JavaScript
reusable APIs
(third-party APIs)
prebuilt Markup
(static site generators)
Traditional Web
Jamstack
Technologies in the stack include JavaScript frameworks, Static Site Generators, Headless CMSs, and CDNs.
Benefits
-
Sequirity
-
Scale
-
Performance
-
Maintainability
-
Portability
-
Developer Experience
2016
release date
10
major releases
+56k
github stars
Next.JS figures
React is about building components
Next.js is about building pages
We didn't want to mess around with libraries, bundlers, configurations...
We wanted the entire solution. We wanted a framework and we wanted a platform.
How to start?
You can start by creating pages directory

pages
In pages every file mapped to a path

pages

about.js


What if you want dynamic route /book/:id

pages

about.js



book

[id].js
What is a page?

pages

about.js


book

[id].js
function About() {
return <h1>About page</h1>
}
Next.js has two forms of pre-rendering: Static Generation and Server-side Rendering
Pre-rendering without data (SG)

pages

about.js


book

[id].js
function About() {
return <h1>About page</h1>
}
export default About;
Static HTML at build time
Pre-rendering with data (SG)

pages

books.js

function Books({ books }) {
// render books
}
// This function gets called at build time
export async function getStaticProps(context) {
// Call an external API endpoint to get posts
const books = await Promise.resolve([1,2,3])
// By returning { props: { books } }, the Books component
// will receive `books` as a prop at build time
return {
props: {
books,
},
}
}
export default Books;
Your page content depends on the external data
Pre-rendering with data (SG)

pages

books.js

function Book({ book }) {
// render a book
}
export async function getStaticPaths() {
// Call an external API endpoint to get books
const books = await Promise.resolve([{id: '1'}, {id: '2'}])
// Get the paths we want to pre-render based on books
const paths = books.map((book) => ({params: { id: book.id }}))
// We'll pre-render only these paths at build time.
// { fallback: false } means other routes should 404.
return { paths, fallback: false }
}
// This also gets called at build time
export async function getStaticProps({ params }) {
// params contains the book `id`.
// If the route is like /book/1, then params.id is 1
const book = await Promise.resolve(`Book #${params.id}`)
// Pass post data to the page via props
return { props: { book } }
}
export default Book
Your page paths depends on the external data

book

[id].js
When should I use Static Generation?
Use Static Generation (with and without data) whenever possible (build once and served by CDN)
Good for: Marketing pages, Blog posts, E-commerce product listings, Help and documentation
"Can I pre-render this page ahead of a user's request?"
Server side Pre-rendering with data

pages

books.js

function Page({ data }) {
// Render data...
}
// This gets called on every request
export async function getServerSideProps(context) {
// Fetch data from external API
const res = await fetch(`https://.../data`)
const data = await res.json()
// Pass data to the page via props
return { props: { data } }
}
export default Page
The page HTML is generated on each request.
Fetching data on the client
import useSWR from 'swr'
function Profile() {
const { data, error } = useSWR('/api/user', fetch)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return <div>hello {data.name}!</div>
}
API Routes
For example, the following API route pages/api/user.js handles a json response:
export default function handler(req, res) {
res.statusCode = 200
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ name: 'John Doe' }))
}
Any file inside the folder pages/api is mapped to /api/*
Dynamic API Routes
For example, the API route `pages/api/post/[pid].js` has the following code:
export default function handler(req, res) {
const {
query: { pid },
} = req
res.end(`Post: ${pid}`)
}
Now, a request to `/api/post/abc` will respond with the text: `Post: abc`.
Built in Middlewares
- req.cookies - An object containing the cookies sent by the request. Defaults to {}
- req.query - An object containing the query string. Defaults to {}
- req.body - An object containing the body parsed by content-type, or null if no body was sent
API routes provide built in middlewares which parse the incoming request (req). Those middlewares are:
Other features
Built-In CSS Support
Adding a Global Stylesheet
import '../styles.css'
// This default export is required in a new `pages/_app.js` file.
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
Also supports: CSS Modules, Sass, Less, CSS-in-JS
Image Optimization
The Automatic Image Optimization allows for resizing, optimizing, and serving images in modern formats like WebP when the browser supports it. This avoids shipping large images to devices with a smaller viewport.
import Image from 'next/image'
<Image
src="/me.png"
alt="Picture of the author"
width={500}
height={500}
/>
Resizing, optimizing, and serving images in modern formats like WebP when the browser supports it.
Images are lazy loaded by default.
Supports:
- Typescript
- Env Variables
- JS features: fetch, Object.assign, async/await, dynamic import...
- AMP
- Internationalization
Deployment
Vercel (Recommended)
- support hybrid pages
- static pages and assets (JS, CSS, images, fonts, etc) will be served from Versel's Edge Network
- Server-side pages and API routes will automatically become isolated Serverless Functions.
Node.js Server
Resourses
Thanks
Questions?
deck
By Yevhen Bezpalko
deck
- 581