We have a react app already built with CRA and Router. We want to implement SSR on it so that we can have proper SEO and social media support. I have seen and tried a number of techniques available for this but none of these seems to work.
We made our app in such a way that a lot of it actually depends upon browser to work properly, for example on the window
object. One technique (kind of) worked but running the code on the server side gives the error;
ReferenceError: 'window' is not defined
The main reason we want to implement SSR is SEO and social media recognition of the site. We are adding meta tags dynamically (using React Hemlet) so facebook, twitter etc. are unable to get the tags.
So now the questions are;
-
Is there a proper way to implement SSR on an already built react site?
-
Is there any alternative we can use? The site has a large amount of resources fetched from remote API endpoints so prerendering is not an option.
4
Answers
You can always implement SSR on a built react site. You will keep your components as unchanged.
However you may need to make modifications at the entry point of your application. And also you will need to create an embedded server in your application which is gonna be your SSR.
For that you will need to make your own webpack configuration.
You may need a developer for that 😉
If you want SSR because of SEO. I would like to use Prerender https://prerender.io/ . This one let our site support SEO even though it’s built by React.
If you’re using an express server you can try the SSR For bots middleware ssr-for-bots I implemented it after stumbling on the same problem,I wanted SSR only because of SEO.
Adding to the first answer, SSR does not execute useEffect(), componentDidMount(), and componentDidUpdate(). However, SSR will execute render(). Therefore, take some time to move
window
anddocument
from render() to useEffect(), componentDidMount(), or componentDidUpdate().If those objects are used in third-party dependencies, don’t import them on the server-side. Instead, on the server-side, render something else (e.g. ComponentA), then on the client-side, use dynamic imports with React lazy to render third-party components with fallback set to ComponentA. For example: