Blog>
Snippets

Server-Side Translation Loading

Implement server-side loading of translations in getServerSideProps for rendering pages with the correct translations.
import { useRouter } from 'next/router';
import en from '../locales/en';
import es from '../locales/es';

export async function getServerSideProps({ locale }) {
  const translations = { en, es };
  return {
    props: {
      messages: translations[locale],
    },
  };
}

function HomePage({ messages }) {
  const router = useRouter();
  const { locale } = router;

  return (
    <div>
      <h1>{messages.title}</h1>
      <p>{messages.description}</p>
    </div>
  );
}

export default HomePage;
This code is using Next.js's 'getServerSideProps' to load the correct translations based on the requested 'locale'. The translations for English ('en') and Spanish ('es') are imported from local files. The 'HomePage' component receives 'messages' as props to display the content in the correct language.
body {
  font-family: 'Arial', sans-serif;
}

h1 {
  color: #333;
}

p {
  color: #666;
}
This is the CSS that styles the 'HomePage' component, setting up the font and colors for the 'h1' and 'p' elements.
<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <title>Translation Example</title>
</head>
<body>
  <div id='root'></div>
</body>
</html>
This is the HTML template that hosts the root of the React application. Here 'Next.js' would inject the server-rendered 'HomePage'.