codermonk
codermonk

Reputation: 43

How do I create user-customizable dynamic url with api-generated content in NextJS+React?

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

  1. Let all routes to be handled by pages/index.js in server.js.
server.get('*', (req, res) => handle(req, res));
  1. In 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
  2. Backend will give back a response basically consisting of a list of components to render for the page and possibly the type and other integral data of page (to help with formatting and retrieving content/layout of the component).
  3. Each of these component then will render render data given by point.3 as necessary.
  4. Tada! The page is rendered without a problem.

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

Answers (1)

HMR
HMR

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

Related Questions