NextJS: How to handle multiple dynamic routes at the root
Next.JS has built in dynamic routing, which shouldn't require you to create a custom server.js file. If you want full compatibility with Next.JS you should use it's dynamic routing instead.
To create a dynamic route in Next.JS you can create pages with names surrounded in square brackets e.g. /pages/[username].js
. This will match all routes on your base domain, so you can set up the example you mentioned with github e.g. http://yourwebsite.com/csbarnes and http://yourwebsite.com/anotherusername.
In the example above you can grab the username in your Next.JS page from the query parameter in getInitialProps
just in the same way as you would with any query string parameters:
static getInitialProps({query}) { console.log(query.username); // the param name is the part in [] in your filename return {query}; // you can now access this as this.props.query in your page}
Next.JS always matches static routes before dynamic routes meaning your /pages/
directory can look like this:
pages/index.js -> (will match http://yourwebsite.com)pages/about.js -> (will match http://yourwebsite.com/about)pages/contact.js -> (will match http://yourwebsite.com/contact)pages/[username].js -> (will match http://yourwebsite.com/[anything_else])
Multiple segments
You can have multiple segment dynamic routes, such as http://website.com/[username]/[repo]
using folders in your pages
directory:
pages/[username].js -> (matches http://yourwebsite.com/[username])pages/[username]/[repo] -> (matches http://yourwebsite.com/[username]/[repo])
In this instance your query object will contain 2 params: { username: ..., repo: ...}
.
Route "prefixes"
You can have multiple dynamic routes with different "prefixes" if you wish by creating folders in your pages
directory. Here is an example folder structure with a website.com/[username]
route and a website.com/teams/[team]
route:
Dynamic number of different segments
You can also have dynamic routes with any number of dynamic segments. To do this you need to use an ellipsis ("...") in your dynamic route file name:
/pages/[...userDetails].js -> (will match http://website.com/[username]/[repo]/[etc]/[etc]/[forever])
In this instance your this.props.userDetails
variable will return an array rather than a string.