Reputation: 43
I need help with customizable dynamic url in Nextjs with React. I have created a Nextjs+React app which utilizes custom server.js to handle routing and 'static' dynamic url. Now I need to migrate this existing setup to be able to use whatever slug the user choose to define from -let's say- CMS and still render the correct page (content will be retrieved from api).
What I think I need to do is this:
Let's we have a user-defined url : www.host.com/some-blog-group/post-of-the-day
pages/index.js
in server.js
. server.get('*', (req, res) => handle(req, res));
page/index.js
, I would need to send a request back to the backend ie. http://backend.com/get-page/some-blog-group/post-of-the-day
Was this train of thought is correct? The existing app is already have tens of pages (setup 'statically' by folder as Next.js recommended and rerouted as necessary in server.js for dynamic routing). Is there a better way to migrate this setup? Or maybe I do not need Nextjs in the beginning?
Upvotes: 4
Views: 1228
Reputation: 39360
which utilizes custom server.js to handle routing
I assume an express server, why not use nextjs routing?
You can create a pages/test/index.js with the following content:
import React from "react";
import Link from "next/link";
class Test extends React.Component {
static async getInitialProps({ query }) {
return { query };
}
render() {
return (
<div>
<Link href="/">
<a>home</a>
</Link>
<pre>
{JSON.stringify(this.props.query, undefined, 2)}
</pre>
</div>
);
}
}
export default Test;
Then create pages/test/[...all].js with the following content:
import Test from "./index";
export default Test;
You should be able to open localhost/test/1/2/3 and get the query as:
{
"all": [
"1",
"2",
"3"
]
}
The index can now apply any logic what to render based on the query. If you need to make a request based on the query you can use getInitialProps to fetch that request.
Upvotes: 0