Easy fetching on Next.js

mkubdev avatar
GitHub Account@mkubdev
LanguageJAVASCRIPT
Published At2022-12-05 17:01:04

Metaphore Name

Easy fetching on Next.js

Share your metaphore story!

Sometimes, we face fetching issue between development and production NODE_ENV.. Next.js need a canonical URL once you use SSR strategy, but it's not required on local development.

A quick utility could be:

  • Create a config/index.tsx at the root of the project
  • Add:
1const dev = process.env.NODE_ENV !== 'production';
2
3export const server = dev
4  ? 'http://localhost:3000'
5  : 'https://your_deployment.server.com';
  • And use this metaphore this way on SSR strategy pages:
1// src/pages/index.tsx
2import type { NextPage } from 'next';
3import Head from 'next/head';
4import React, { forwardRef, useEffect, useRef } from 'react';
5
6// Import the config
7import { server } from 'config';
8
9const Homepage: NextPage = ({ data }) => {
10  return (
11    <>
12      <Head>
13        <title>Homepage</title>
14        <meta name="description" content="Homepage" />
15        <link rel="icon" href="/favicon.ico" />
16      </Head>
17      <div>{data}</div>
18    </>
19  );
20};
21
22Homepage.displayName = 'Homepage';
23export default Homepage;
24
25export async function getServerSideProps(context) {
26  const res = await fetch(`${server}/your/endpoint/1`); // use server export here!!
27  const data = await res.json();
28
29  return {
30    props: {
31      data, // will be passed to the page component as props
32    },
33  };
34}
  • Once you ship the app in production server, just update config/index.tsx accordingly

A demo/repos link

No response

Share This Story