1.0.18 • Published 4 years ago
next-lnk v1.0.18
Express-style routing for Next.js
Requires next>=9.1.7
#1 Add /project/routes.js
const routes = [
// component is the file name (without extension) inside /pages/
// See https://www.npmjs.com/package/path-to-regexp for more info about paths
{ component: 'index', path: '/' },
{ component: 'page', path: '/post/:slug-:id(\\w+)' },
{ component: 'category', path: '/category/:slug-:id(\\w+)' },
{ component: 'login', path: '/login' }
]
module.exports = routes
#2 Installation on server (request handler)
in /project/server.js
// ...
const { lnkInstall } = require('next-lnk')
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
// ➕
lnkInstall(require('./routes'), { server, app })
server.all('*', (req, res) => {
return handle(req, res)
})
server.listen(PORT)
})
#3 Installation on client
in /project/src/pages/_app.js
import App from 'next/app'
import { lnkInstall } from 'next-lnk'
// ...
lnkInstall(require('../../routes')) // ➕
// ...
Usage is similar to next/link
import Link from 'next-lnk'
import Router, { useRouter } from 'next/router'
<Link to="/post/example-slug-YXqcO2">
<a>Post</a>
</Link>
// Installing next-lnk on the client (#3 _app.js) adds methods to the original Router
Router.pushTo('/post/example-slug-YXqcO2')
Router.replaceTo('/post/example-slug-YXqcO2')
To read the query parameters:
import { useRouter } from 'next/router'
const ExampleComponent = () => {
const router = useRouter()
console.log(router.query)
// > { slug: "example-slug", id: "YXqcO2" }
return <div>{JSON.stringify(router.query, null, 2)}</div>
}