Ryan Dhungel
Ryan Dhungel

Reputation: 3775

How to remove subfolder name from Next Js URL?

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?

Upvotes: 6

Views: 1898

Answers (1)

Andrei
Andrei

Reputation: 1863

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).

Upvotes: 1

Related Questions