React: Error handling with server side rendering

Created on 23 Apr 2015  Â·  6Comments  Â·  Source: facebook/react

Hi.

When running React.renderToString() on my node.js server I get no error messages when there is a error. Instead everything just stops, and the browser get no response. I've added propTypes, and they give me errors. But if a key inside a object isn't there, there is no error message. This is a big problem when I'm trying to learn React to other developers. Is there a callback or anything to detect errors in React.renderToString?

Thanks.

Most helpful comment

Hi @mmahalwy,

Something like this should work:

import React from 'react';
import ReactDOMServer from 'react-dom/server';
import HtmlDocument from './HtmlDocument';
import { RouterContext } from 'react-router';
import { Provider } from 'react-redux';

export default function render(renderProps, store, res, next) {
    const assets = webpackIsomorphicTools.assets();

    try {
        const markup = ReactDOMServer.renderToString(
            <Provider store={store}>
                <RouterContext {...renderProps} />
            </Provider>
        );

        const html = ReactDOMServer.renderToStaticMarkup(
            <HtmlDocument
                markup={markup}
                assets={assets}
                params={renderProps.params}
            />
        );

        res.send(`<!DOCTYPE html>${html}`);
    }
    catch (err) {
        next(err);
    }
}

All 6 comments

Glad you figured it out – this isn't React-specific; any error you throw in your component bubbles up to renderToStaticMarkup so however you handle errors in your app, you have to do here too.

@kennethaa link not working. Any example?

Hi @mmahalwy,

Something like this should work:

import React from 'react';
import ReactDOMServer from 'react-dom/server';
import HtmlDocument from './HtmlDocument';
import { RouterContext } from 'react-router';
import { Provider } from 'react-redux';

export default function render(renderProps, store, res, next) {
    const assets = webpackIsomorphicTools.assets();

    try {
        const markup = ReactDOMServer.renderToString(
            <Provider store={store}>
                <RouterContext {...renderProps} />
            </Provider>
        );

        const html = ReactDOMServer.renderToStaticMarkup(
            <HtmlDocument
                markup={markup}
                assets={assets}
                params={renderProps.params}
            />
        );

        res.send(`<!DOCTYPE html>${html}`);
    }
    catch (err) {
        next(err);
    }
}

@kennethaa thanks! much appreciated! :)

@kennethaa thanks for your solution, which is out of the box!

Was this page helpful?
0 / 5 - 0 ratings