Wednesday, 3 May 2017

How to build custom / dynamic routing in Next.js React Framework

I am wanting to implement dynamic routing within the framework so that routes are generated depending on what pages we have in the CMS. I have read the documentation and https://github.com/zeit/next.js#custom-server-and-routing looks like it will do the job.

const express = require('express')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare()
.then(() => {
  const server = express()

  server.get('/', (req, res) => {
    return app.render(req, res, '/index', req.query)
  })

  server.get('/b', (req, res) => {
    return app.render(req, res, '/test', req.query)
  })

  server.get('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(3000, (err) => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})

My question is, where does this code go with in the project? I have tried creating ./server/server.js but then need to update my start scripts in package.json but these will need to point to the dist version as in ./dist/server/server.js?

"scripts": {
    "build": "next build",
    "release": "fly release",
    "pretestonly": "fly pretest",
    "testonly": "cross-env NODE_PATH=test/lib jest \\.test.js",
    "posttestonly": "fly posttest",
    "pretest": "npm run lint",
    "test": "npm run testonly -- --coverage --forceExit --runInBand --verbose --bail",
    "coveralls": "nyc --instrument=false --source-map=false report --temp-directory=./coverage --reporter=text-lcov | coveralls",
    "lint": "standard 'bin/*' 'client/**/*.js' 'examples/**/*.js' 'lib/**/*.js' 'pages/**/*.js' 'server/**/*.js' 'test/**/*.js'",
    "prepublish": "npm run release",
    "precommit": "lint-staged",
    "dev": "node ./dist/server/server.js",
    "start": "NODE_ENV=production node ./dist/server/server.js"
  },

./dist/server/server.js path doesn't exist even after running yarn run build



via Stretch0

No comments:

Post a Comment