next.js: Hot Reloading not working in Next.js 9 using custom routing, styled components and withApollo example

Bug report

We are running "dev": "cross-env NODE_ENV=development babel-node src/server.js", to start nextjs in dev mode from our server.js file

We see the compiled successfully message when making changes to the pages/components folder image

but we do not see any changes or renders on the page until we refresh the page

import express from "express";
import "isomorphic-fetch";
import next from "next";
import projectConfig from "./config";

import { initializeApollo } from "./lib/nextApollo";
import gql from "graphql-tag";

const compression = require("compression");
const apiHost = projectConfig.apiHost;
const currentHost = projectConfig.host;
const env = projectConfig.env;

// export interface Global extends NodeJS.Global {
//   document: Document;
//   window: Window;
//   DEVELOPMENT: any;
//   FOLDER: any;
// }

// declare var global: Global;

global.DEVELOPMENT = projectConfig.env == "DEV" ? true : false;
const dev = global.DEVELOPMENT ? true : false;
const folder = global.DEVELOPMENT ? "src" : "dist";

console.log("IS DEVELOPMENT", dev, "FOLDER", folder);

const app = next({ dev, dir: folder });

const handle = app.getRequestHandler();
const server = express();

server.use(compression());

Describe the bug

Next.js, not rerendering page when changes are made to the app.

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Run app
  2. Go to page in a browser
  3. Make a change on page
  4. See compiled successfully but no rerender

Expected behavior

Hot reloading should rerender the page

System information

  • OS: Mac and windows
  • Browser all Browsers
  • Version of Next.js: 9.3 and 9.5
  • Version of Node.js: 12

Code Example

export const resolvers = {
    Mutation: {
        setGlobalVolume: (_, { volume }, { cache }) => {
            // cache.writeData({ data: { globalVolume: volume } });
            return null;
        },
        setGlobalSrc: (_, { id }, { cache }) => {
            // cache.writeData({ data: { globalSrcId: id } });
            return null;
        },
    },
};

const authLink = setContext((_, { headers }) => {
    if (projectConfig.env === "DEV") {
        // get the authentication token from local storage if it exists
        const token = isBrowser
            ? window.localStorage
                ? window.localStorage.getItem("jwt")
                : ""
            : "";

        // return the headers to the context so httpLink can read them
        return {
            headers: {
                ...headers,
                authorization: token ? `Bearer ${token}` : "",
            },
        };
    } else {
        return {
            headers: {
                ...headers,
            },
        };
    }
});

// https://www.apollographql.com/docs/react/caching/cache-configuration/
const apolloCache = new InMemoryCache({
    dataIdFromObject(responseObject) {
        switch (responseObject.__typename) {
            case "Bite":
                return `Bite:${responseObject._id}`;
            case "Playlist":
                return `Playlist:${responseObject._id}`;
            case "Category":
                return `Category:${responseObject._id}`;
            case "User":
                return `User:${responseObject._id}`;
            default:
                return defaultDataIdFromObject(responseObject);
        }
    },
    typePolicies: {
        Bite: {
            fields: {
                audio: {
                    original: {
                        merge(existing, incoming, { mergeObjects }) {
                            return existing._id;
                        },
                    },
                },
            },
        },
        Query: {
            queryType: true,
            fields: {
                web: {
                    merge: true,
                    queryType: true,
                },
                twitch: {
                    merge: true,
                    queryType: true,
                },
            },
        },
    },
});

export function initializeApollo(initialState = {}) {
    const _apolloClient = apolloClient || createApolloClient();

    // If your page has Next.js data fetching methods that use Apollo Client, the initial state
    // gets hydrated here
    if (initialState) {
        // Get existing cache, loaded during client side data fetching
        const existingCache = _apolloClient.extract();
        // Restore the cache using the data passed from getStaticProps/getServerSideProps
        // combined with the existing cached data
        _apolloClient.cache.restore({ ...existingCache, ...initialState });
    }
    // For SSG and SSR always create a new Apollo Client
    if (typeof window === "undefined") return _apolloClient;
    // Create the Apollo Client once in the client
    if (!apolloClient) apolloClient = _apolloClient;

    return _apolloClient;
}

export function useApollo(initialState) {
    const store = useMemo(() => initializeApollo(initialState), [initialState]);
    return store;
}

_app.js

import React from "react";
import { ApolloProvider } from "@apollo/client";
import { useApollo } from "../lib/nextApollo";
import * as ReactGA from "react-ga";

import { Helmet } from "react-helmet";

import { Themes } from "@blerp/design";
import { colors } from "../components/theme/Theme";
import { ThemeProvider } from "styled-components";

// https://github.com/vercel/next.js/tree/canary/examples/with-apollo For apollo + nextjs example
export default function App({ Component, pageProps }) {
    const apolloClient = useApollo(pageProps.initialApolloState);

    return (
        <ApolloProvider client={apolloClient}>
            <ThemeProvider
                theme={{
                    ...Themes.mainTheme,
                    colors: colors,
                    mode: "light",
                }}
            >
                <>
                    <Helmet defaultTitle='Blerp' titleTemplate='%s' />
                    <Component {...pageProps} />
                </>
            </ThemeProvider>
        </ApolloProvider>
    );
}

_documents.js

    static async getInitialProps(ctx) {
        const sheet = new ServerStyleSheet();
        const originalRenderPage = ctx.renderPage;
        try {
            ctx.renderPage = () =>
                originalRenderPage({
                    enhanceApp: App => props =>
                        sheet.collectStyles(<App {...props} />),
                });

            const initialProps = await Document.getInitialProps(ctx);
            return {
                ...initialProps,
                styles: (
                    <>
                        {initialProps.styles}
                        {sheet.getStyleElement()}
                    </>
                ),
            };
        } finally {
            sheet.seal();
        }
    }

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Reactions: 18
  • Comments: 47 (4 by maintainers)

Commits related to this issue

Most upvoted comments

@JoseFMP for me it was the casing of a folder that I was referencing within my app. There was a folder with all lowercase, and I was referencing it in a file as capitalized. The app still built (and deployed) but Fast Refresh wouldn’t work (or any refresh). As soon as I fixed the casing, Fast Refresh returned. For this example, the only (perhaps unhelpful) help I can offer is to scrupulously check all your file imports and make sure they match. Understand that my comment does not wholly reflect the open issue, just what I experienced.

Following. We’re having a similar issue.

I confirm this issue. Also I noticed the following messages in browser console: [Fast Refresh] rebuilding [Fast Refresh] done And triangular indicator of updating at right bottom corner of screen appears and disappears, but nothing happened - changes do not apply.

Same issue, but neither solution helped in my case.

For me my main index page hot reloads correctly, but all other pages has the same affect as reported here.

Console says it’s doing a “Fast refresh” but nothing updates.

Any updates/solution on this?

next@10.0.7 react@17.0.1

I had the same issue with nextjs v10.0.5. Application reflecting changes only in _document file and after that routes it stops reflecting at all other routes. triangle indicator showing after fast refresh in the console but changes not reflecting at all I was a need to manually refresh the browser in order to see changes. SOLUTION IN MY CASE I find out this problem was related to my react version I deleted react and react-dom from paskage.json and reinstalled it again with a newer version.

Okay… so for me it was a very silly issue - I had a component nested in a folder controls but I was referencing it from another component as from ./Controls. The casing was the issue - however, everything was rendering / displaying as normal (just no fast refresh), and there were no warnings in the console. I received a warning only after I took a child component in controls and rendered it directly from the component further up the tree. I understand these are separate issues, but just in case someone stumbles across this: casing matters for Fast Refresh (but not always for the build), and if it’s nested - it may swallow the warning.

Having a similar issue. The “reload triangle” shows in the bottom corner and fast refresh is logged in console, but changes made to all imported components do not reflect accordingly.

Double-checked the casing of import paths and issue still persists. Non-imported components in the same file are not affected and update as intended.

next@12.1.0, react@17.0.2

Edit: Turns out it wasn’t relevant to this issue, I somehow never learned I should declare components using <Component/> instead of { Component() }. Rookie mistake, but hope it helps someone coming across the same problem.

Happened to me too. I was just starting with Next.js, using this tutorial: https://auth0.com/blog/next-js-practical-introduction-for-react-developers-part-1/

Created the three components in the example, tried to change the backgroundColor, and it stopped responding to changes. Even after refresh, the color was outdated. I notice it always responds to one change after a server restart, and then breaks.

Encountered a similar or same bug in next@10.2.2. On a rebuild that appeared to trigger a refresh, but where my changes were not reflected, I noticed I got a “build” event over the webpack-hmr WS connection but the hash key was the same after making changes and saving, so presumably the client refused to refresh on the grounds that (bundle?) hash had not changed.

Opting out of webpack 5 with the following next.config.js file seems to have fixed it:

module.exports = {
  future: {
    webpack5: false,
  },
}

@MarkLyck you might try the above and see if it does anything for you as we had close next and react versions.

I solved it, in my case. When I run with “yarn start” or “npm run start”, it is used in the production environment and does not reload build changes. We have to use “yarn run dev” or “npm run dev”.

Here my 2cents, I was having hot reload problems ONLY in a component and got it resolved changing the first capital letter of my component .js file to a lowercase one.

Having the first capital letter at the filename was causing the hot reload problem.

...
/components
|____ComponentFile.js
...
export default function ComponentFile(){
   ...
}

After changing the capital letter to a lower case one, the hot reload function on the component started to work again.

...
/components
|____componentFile.js
...
export default function ComponentFile(){
   ...
}

package.json

"next": "12.1.1",
"react": "17.0.2",

Had the same/similar issue. The console would show that a refresh was occurring but the components would not refresh. Restarting the server would refresh everything, but hot reloading would not work. Interestingly, it seems to only affect components nested at least three layers deep.

I disabled webpack 5 from the config and now everything works.

next@11.0.0, react@17.0.2

I was/am having this issue and have been for the last 2 weeks or so. So if you want to force case checking on file imports, its worth using: eslint import/no-unresolved This rule is case sensitive by default. I had disabled this around 2 weeks ago!! Dog!!

I have a few select components in my application that will not only not hot reload but won’t reload on a full refresh either. I need to run a completely new build to see reflected changes … any quick thought on why this might be? The only thing that jumps out is that I’m doing a dynamic import in the parent component with ssr: false however commenting this component out does nothing. I’m also getting no ‘Fast Refresh’ indication in the console.

I’m facing a similar issue, but only in SSG pages.

I was/am having this issue and have been for the last 2 weeks or so. So if you want to force case checking on file imports, its worth using: eslint import/no-unresolved This rule is case sensitive by default. I had disabled this around 2 weeks ago!! Dog!!

this helped me instead of importing the regular way do const { default: About } = require(“…/components/About”);

I am having the same issue across multiple computers, disabling webpack 5 doesn’t seem to have fixed it.

@garretteklof you saved me so much pain, thank you 💯

This was indeed the reason why my changes weren’t being recompiled and refreshed in the browser. I had a folder with a capital letter as the first letter, but then I imported it in lower case.

The super confusing thing was that I could restart the server manually and I would then see my changes, but that would never have led me to understand that the root of the problem was a casing issue.