Bikin Web SSR dengan Next.JS & Strapi (Part 3)
3 min readNov 24, 2018
Post sebelumnya udah dibahas gimana bikin API pakai Strapi, nah kali ini bakal bikin front-end pakai NextJS. Langsung aja gan.
Setup NextJS
Pertama install dulu create-next-app.
npm install -g create-next-app
Lalu generate project baru dengan create-next-app
create-next-app --example with-styled-components blog-frontend
Running NextJS
Kalau sudah ter-generate, masuk ke directory yang kita bikin, lalu jalankan
npm run dev
Hello World ala NextJS:
Layouting
Tambah file server.js & routes.js
:
/* server.js */const express = require('express')
const next = require('next')
const LRUCache = require('lru-cache')const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const routes = require('./routes')
const handle = app.getRequestHandler()
const handler = routes.getRequestHandler(app)// This is where we cache our rendered HTML pages
const ssrCache = new LRUCache({
max: 100,
maxAge: 1000 * 60 * 60 // 1hour
})app.prepare()
.then(() => {
const server = express()
server.use(handler)server.get('*', (req, res) => {
return handle(req, res)
})server.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})/*
* NB: make sure to modify this to take into account anything that should trigger
* an immediate page change (e.g a locale stored in req.session)
*/
function getCacheKey (req) {
return `${req.url}`
}async function renderAndCache (req, res, pagePath, queryParams) {
const key = getCacheKey(req)// If we have a page in the cache, let's serve it
if (ssrCache.has(key)) {
res.setHeader('x-cache', 'HIT')
res.send(ssrCache.get(key))
return
}try {
// If not let's render the page into HTML
const html = await app.renderToHTML(req, res, pagePath, queryParams)// Something is wrong with the request, let's skip the cache
if (res.statusCode !== 200) {
res.send(html)
return
}// Let's cache this page
ssrCache.set(key, html)res.setHeader('x-cache', 'MISS')
res.send(html)
} catch (err) {
app.renderError(err, req, res, pagePath, queryParams)
}
}
routes.js
:
const nextRoutes = require('next-routes')
const routes = module.exports = nextRoutes()routes.add('index', '/')
routes.add('blog', '/blog/:slug')
Bikin folder components
kemudian bikin lagi folder Nav components/Nav/index.js
import Link from 'next/link'
import styled from 'styled-components'const Wrapper = styled.nav`
padding: 15px;
border-bottom: 1px solid #ddd;
display: flex;
background: #fd4f5d;
a {
padding: 0 15px;
color: #FFF;
}
`const Nav = () => (
<Wrapper>
<Link href='/'><a>Home</a></Link> |
<Link href='/about' prefetch><a>About</a></Link> |
<Link href='/contact' prefetch><a>Contact</a></Link>
</Wrapper>
)export default Nav
Tambahin Fetch API
File services/blogs/index.js
import fetch from 'isomorphic-fetch'export function getPosts() {
return fetch('http://0.0.0.0:1337/blogs')
}export function getPost(slug) {
return fetch(`http://0.0.0.0:1337/blogs/${slug}`)
}
Untuk yang belum bisa running strapi, bisa pakai yang ini:
import fetch from 'isomorphic-fetch'
export function getPosts() {
return fetch('https://jsonplaceholder.typicode.com/posts')
}
export function getPost(slug) {
return fetch(`https://jsonplaceholder.typicode.com/posts?title=${slug}`)
}
Source code aplikasi ada di https://github.com/waskito/jogjajs-frontend.