Search code examples
node.jsreactjsreact-routerisomorphic-javascriptserver-rendering

StaticRouter not working with dynamic routes in Server render


I have a dynamic parameter in a route. When I directly open the URL it throws an error.

To make my server aware of the route I m using static router in server rendering.

Here's my server render code:

const serverRender = (req, res) => {
  const routes = [
    {
        path: '/',
        exact: true,
        component: Signin
    }
    {
        path: '/shared/:id',
        component: Shared,
        fetchInitialData: path => sharedInitialData(path)
    }
  ];

    const activeRoute = routes.find(route => matchPath(req.url, route)) || {}

    const promise = activeRoute.fetchInitialData ? activeRoute.fetchInitialData(req.path) : Promise.resolve()

    const theme = createMuiTheme({
        palette: {
            primary: blue
        },
        typography: {
            useNextVariants: true
        }
    });

    const sheets = new ServerStyleSheets();

    promise.then(data => {
        const app = renderToString(
            sheets.collect(
                <ThemeProvider theme={theme}> 
                    <Provider store={store}>
                        <StaticRouter location={req.url} context={{data}}>
                            <App />
                        </StaticRouter>
                    </Provider>
                </ThemeProvider>
            )
        )

        const css = sheets.toString();
        res.send(renderFullPage(app, css))
    })
    .catch(error => console.log(error));
}


const renderFullPage = (html, css) => `
    <!DOCTYPE html>
    <html>
        <head>
            <style>
                a{
                    text-decoration: none;
                    color: #000
                }
                ${css}
            </style>
        </head>
        <body>

            <div id="root">${html}</div>

            <script src="main.js"></script>

        </body>
    </html>
`


async function sharedInitialData(path) {
  const id = path.split('/').pop();
  return id;


}

When I open /shared/12345 I get the error in console. Uncaught SyntaxError: Unexpected token < main.js:1

main.js is my bundle file generated by webpack

My bundle file gets populated with HTML instead of js. I think this is the problem


Solution

  • I think that the problem is with the path in <script> you've given in your renderFullPage(). I think your main.js is not accessible. can you try adding a slash(/) in the path?

    try changing <script src="main.js"></script> to <script src="/main.js"></script>