skip to Main Content

I want server side render in my react project show that google bot can read the content of react project and my site can easily rank

I want code and method how can I do that Server Side Rendering please help me regarding this project
I tried Hydrate Root which is not working in my project

2

Answers


  1. If you want to SSR in your react project.You have to use Next.js library.
    Documentation

    Login or Signup to reply.
  2. You have 2 option if you want to SSR in your react project

    1. Used Nextjs
    2. Used express and react-dom-server

    But i suggest Nextjs is convenient option

    for 2 option used express and react-dom-server

    this way you can achive

    Add the following code to server.js

    const express = require('express');
    const path = require('path');
    const React = require('react');
    const ReactDOMServer = require('react-dom/server');
    const App = require('./src/App').default;  // Adjust path if App.js is 
    located elsewhere
    
    const app = express();
    
    // Serve static files from the 'build' directory
    app.use(express.static(path.resolve(__dirname, 'build')));
    
      app.get('*', (req, res) => {
      // Render the App component to a string
      const appHtml = ReactDOMServer.renderToString(<App />);
    
      // Generate the full HTML response
      const html = `
            <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial- 
      scale=1.0">
        <title>Your SSR React App</title>
        <link rel="stylesheet" href="/static/css/main.css">
      </head>
      <body>
        <div id="root">${appHtml}</div>
        <script src="/static/js/bundle.js"></script>
      </body>
    </html>
        `;
    
     // Send the response
      res.send(html);
     });
    
     // Start the server
      app.listen(3000, () => console.log('Server is running on 
        http://localhost:3000'));
    

    Enable Hydration on the Client Side

    import React from 'react';
    import { hydrateRoot } from 'react-dom/client'; // `hydrateRoot` 
    ensures client-side functionality
    import App from './App';
    
    hydrateRoot(document.getElementById('root'), <App />);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search