Goal: I would like to achieve github style routing, where
abcd
ingithub.com/abcd
could resolve to a user profile page or a team page.
I currently have a version that sort of works (see below). Unfortunately I am occasionally getting a white page flash when navigating between 2 dynamic routes.
My server file looks like:
const express = require('express');
const next = require('next');
const { parse } = require('url');
const resolveRoute = require('./resolveRoute');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const nextApp = next({
dev,
});
const nextHandle = nextApp.getRequestHandler();
const STATIC_ROUTES = [
'/about',
'/news',
'/static',
];
const DYNAMIC_ROUTE_MAP = {
user: '/[user]',
team: '/teams/[team]',
};
nextApp.prepare().then(() => {
const server = express();
server.get('*', async (req, res) => {
// pass through next routes
if (req.url.indexOf('/_next') === 0) {
return nextHandle(req, res);
}
// pass through static routes
if (
req.url === '/' ||
STATIC_ROUTES.map(route => req.url.indexOf(route) === 0).reduce(
(prev, curr) => prev || curr,
)
) {
return nextHandle(req, res);
}
// try to resolve the route
// if successful resolves to an object:
// { type: 'user' | 'team' }
const resolvedRoute = await resolveRoute(req.url);
if (!resolvedRoute || !resolvedRoute.type) {
console.error('🛑 Unable to resolve route...');
return nextHandle(req, res);
}
// set query
const { pathname } = parse(req.url);
const paths = pathname.split('/').filter(path => path.length > 0);
const query = {
[resolvedRoute.type]: paths.length > 0 ? paths[0] : null,
};
// render route
return nextApp.render(
req,
res,
DYNAMIC_ROUTE_MAP[resolvedRoute.type],
query,
);
});
server.listen(port, err => {
if (err) throw err;
console.log(`🌎 Ready on http://localhost:${port}`);
});
});
I'm wondering if there is a better way to handle this or if I need to move away from NextJS.
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])
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: ...}
.
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:
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.
One addition regarding usage of SSR and SSG pages and you need to differentiate those with dynamic URLs by adding the '-ssr' prefix to an URL.
For example, you need some pages to be SSR, then you can create under the pages an ssr folder where you could put the page [[...path]].js with getServerSideProps. Then you could use such rewrite in the next.config.js under async rewrites() {:
{
source: '/:path*/:key-ssr', destination: '/ssr/:path*/:key-ssr'
}
that covers such URLs:
etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With