Create dynamic pages in NextJS

NextJS

Create dynamic pages that fetch their content from an API in NextJS

This is useful in dynamic websites where the contents of a page is fetched from a backend API based on the URL.

In your pages directory, create a new [slug].js - or [slug].tsx if you are using Typescript -

javascript

import React from "react"; export default class DynamicPage extends React.Component { static async getInitialProps({ query }) { try { const url = `https://some-url.com/${query.slug}` const content = await fetch(url); return { content }; } catch (error) { return { error }; } } render() { const { error, content } = this.props; if (error) { return <h1>Error</h1>; } return ( <p>{content}</p> ); } }