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}`);
});
2
Answers
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 :
If it still doesn’t solve the problem. Try reading through this thread – using-redux-with-redux-persist-with-server-side-rendering
Thank you.
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.