Blog>
Snippets

SEO Optimization Techniques in SSR

Showcase how to optimize SEO in a server-side rendered application by enhancing the returned HTML from TanStack Router with meta tags and structured data.
import express from 'express';
import { renderToString } from 'react-dom/server';
import React from 'react';
import { StaticRouter } from 'react-router-dom/server';
import App from './src/App';

const app = express();

app.use('^/$', (req, res, next) => {
  const context = {};
  const app = renderToString(
    <StaticRouter location={req.url} context={context}>
      <App />
    </StaticRouter>
  );

  const SSR_HTML = `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <meta name='description' content='Your application description for better SEO'>
    <title>Your Application Title</title>
</head>
<body>
    <div id="root">${app}</div>
</body>
</html>`;

  res.setHeader("Content-Type", "text/html");
  res.send(SSR_HTML);
});

app.listen(3000, () => {
  console.log('Server started on http://localhost:3000');
});
This code snippet demonstrates setting up a basic server-side rendered (SSR) application using Express.js and React with TanStack Router (formerly known as React Router) for server-side routing. It renders the application to a string using `renderToString` and sends back a fully formed HTML response. The response includes essential SEO optimizations such as setting the language with `<html lang="en">`, meta charset, viewport for responsive design, and a meta description for improving page summary in search engine results. The title tag is also set for defining the page's title in search results and the browser tab. This SSR approach helps in improving SEO by serving crawlers a fully rendered page.
const MetaTagsRouter = ({ title, description, children }) => (
  <StaticRouter context={{}}>
    <Helmet>
      <title>{title}</title>
      <meta name="description" content={description} />
    </Helmet>
    {children}
  </StaticRouter>
);
This piece of code introduces a component `MetaTagsRouter` utilizing `StaticRouter` and `Helmet` (a component for managing changes to the document head) to dynamically adjust meta tags like title and description based on the current route. This is particularly useful for SEO in server-side rendered applications, where different routes may require different meta tags to accurately describe and optimize the content for search engines. By including this component at the top level of each page component, you can ensure that each route in your SSR application has optimized SEO metadata.