skip to Main Content

My React Application works fine in Client-side rendering.I’m trying to Implement Server-side rendering in my app for SEO purposes.

when I run server.js file I got an error.

How can I solve this issue?
Server.js

    import path from 'path';
import fs from 'fs';

const PORT = 8080;
const app = express();

const router = express.Router();
app.use(express.json());

const serverRenderer = (req, res, next) => {
    const content = ReactDOMServer.renderToString(
<Provider store={store}>
<PresistGate presist={presist}>
        <StaticRouter location={req.url} context={{}}>
            <App />
        </StaticRouter>
</PresistGate >
</Provider>
    );
    fs.readFile(path.resolve('../dist/index.html'), 'utf8', (err, data) => {
        if (err) {
            console.error(err);
            return res.status(500).send('An error occurred');
        }
        return res.send(data.replace('<div id="root"></div>', `<div id="root">${content}</div>`));
    });
};
router.use('*', serverRenderer);

router.use(express.static(path.resolve(__dirname, '..', 'dist'), { maxAge: '30d' }));

// tell the app to use the above rules
app.use(router);

// app.use(express.static('./build'))
app.listen(PORT, () => {
    console.log(`SSR running on port ${PORT}`);
});

enter image description here

2

Answers


  1. I might be very late to answer but,

    In case of NextJs, the issue is solved by using storage conditionally based on it is client side or server side for persisting the states.
    As for the matter of fact the ‘window is not defined on server side’.

    Example code :

    const isClient = typeof window !== "undefined";
    
    let mainReducer;
    if (isClient) {
     const { persistReducer } = require("redux-persist");
     const storage = require("redux-persist/lib/storage").default;
    
     const rootPersistConfig = {
       key: "root",
       storage: storage,
       blacklist: ["countries"],
     };
    
     const countriesPersistConfig = {
       key: "countries",
       storage: storage,
       whitelist: ["countriesList"],
     };
    
     /* COMBINE REDUCERS */
     const combinedReducers = combineReducers({
       countries: persistReducer(countriesPersistConfig, countries),
     });
    
     mainReducer = persistReducer(rootPersistConfig, combinedReducers);
    } else {
     mainReducer = combineReducers({
       countries,
     });
    }
    

    If it still doesn’t solve the problem. Try reading through this thread – using-redux-with-redux-persist-with-server-side-rendering

    Thank you.

    Login or Signup to reply.
  2. That error happens because you want to create the localstorage object on the server side, so that’s the reason for warning.

    I did the following to solve.

    import createWebStorage from 'redux-persist/lib/storage/createWebStorage';
    const createNoopStorage = () => {
       return {
          getItem(_key: any) {
             return Promise.resolve(null);
          },
          setItem(_key: any, value: any) {
             return Promise.resolve(value);
          },
          removeItem(_key: any) {
             return Promise.resolve();
          },
       };
    };
    const storage = typeof window !== 'undefined' ? createWebStorage('local') : createNoopStorage();
    
    
    const reducers = combineReducers({
       YourReducers:xxxx.reducer
     });
    
    const persistConfig = {
       key: 'root',
       storage //here we will put the storage variable that we created above
    };
    .... and here all the rest of your configuration...
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search