1.0.18 • Published 4 years ago

next-lnk v1.0.18

Weekly downloads
-
License
MIT
Repository
-
Last release
4 years ago

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>
}
1.0.18

4 years ago

1.0.17

4 years ago

1.0.15

4 years ago

1.0.14

4 years ago

1.0.13

4 years ago

1.0.12

4 years ago

1.0.11

4 years ago

1.0.9

4 years ago

1.0.10

4 years ago

1.0.8

4 years ago

1.0.7

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.2

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago