6

I have created bunch of files in pages/user/ folder. I can access them with the following URL:

http://localhost:3000/user/signup
http://localhost:3000/user/signin
http://localhost:3000/user/profile

What I would like to do is remove user/ part so that URL looks like this:

http://localhost:3000/signup
http://localhost:3000/signin
http://localhost:3000/profile

I will be adding more folders inside pages later for posts etc. What is the best way to achieve this?

1 Answer 1

1

For this you need to use a custom server.js. See the Custom server and routing part of the documentation.

Your code would look something like this:

const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')

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

app.prepare().then(() => {
  createServer((req, res) => {
    // Be sure to pass `true` as the second argument to `url.parse`.
    // This tells it to parse the query portion of the URL.
    const parsedUrl = parse(req.url, true)
    const { pathname, query } = parsedUrl

    if (pathname === '/signup') {
      app.render(req, res, '/user/signup', query)
    } else if (pathname === '/signin') {
      app.render(req, res, '/user/signin', query)
    } else {
      handle(req, res, parsedUrl)
    }
  }).listen(3000, err => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})

Another option is to move the files themselves within the ./pages folder, but I suspect you want to avoid doing this (hence your question).

Sign up to request clarification or add additional context in comments.

1 Comment

Ya this works but requires manually typing all the routes. Is there a better solution?

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.