2

I want 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 does not exist, even after running yarn run build

2
  • just dump the code into ./server.js and edit the scripts Commented May 3, 2017 at 21:37
  • Don't I want to run the transpiled version from the ./dist folder? Commented May 3, 2017 at 22:39

1 Answer 1

2

Next.js doesn't transpile custom server code, so you would start it like so:

"dev": "node ./server/server.js",
"start": "NODE_ENV=production node ./server/server.js"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.