Contact
← Back to Topics

Server Side Rendering

Technique for rendering app content on the server to improve initial load performance.

About Server Side Rendering

Server Side Rendering (SSR) is a technique where web content is generated on the server before being sent to the mobile client. This approach is used in mobile development to improve initial load times, SEO, and performance on devices with limited processing power.

Key Features

  • Improved initial load time
  • Better SEO for web content
  • Reduced client-side processing
  • Progressive enhancement
  • Pre-rendered content

Code Example

// Server-side rendering with React Native for Web example

// Server.js (Node.js with Express)
import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { AppRegistry } from 'react-native-web';
import App from './App';

const app = express();

// Register the app
AppRegistry.registerComponent('App', () => App);

app.get('/', (req, res) => {
  // Get the React Native for Web UI
  const { element, getStyleElement } = AppRegistry.getApplication('App', {});
  
  // Render the React application to a string
  const html = renderToString(element);
  
  // Get the styles
  const css = renderToString(getStyleElement());
  
  // Send the rendered page back to the client
  res.send(`
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Server-side Rendered React Native</title>
        ${css}
      </head>
      <body>
        <div id="root">${html}</div>
        <script src="bundle.js"></script>
      </body>
    </html>
  `);
});

// Start the server
app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

// App.js (React Native component)
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
  return (
    <View style={styles.container}>
      <Text style={styles.text}>This is server-side rendered React Native</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    height: '100vh',
    backgroundColor: '#F5FCFF',
  },
  text: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});