React-router: TypeError: Cannot read property 'query' of null - react-router/node_modules/history/lib/useQueries.js:43:22

Created on 28 Sep 2015  路  21Comments  路  Source: ReactTraining/react-router

Hi,

We tried to migrate our app from react-router 0.13 to 1.0 and we got some big errors.

{"error":"TypeError: Cannot read property 'query' of null\n at .../node_modules/react-router/node_modules/history/lib/useQueries.js:43:22\n at .../node_modules/react-router/lib/useRoutes.js:252:15\n at .../node_modules/react-router/lib/useRoutes.js:88:15\n at .../node_modules/react-router/lib/useRoutes.js:124:15\n at done (.../node_modules/react-router/lib/AsyncUtils.js:49:19)\n at .../node_modules/react-router/lib/AsyncUtils.js:55:7\n at getComponentsForRoute (.../node_modules/react-router/lib/getComponents.js:9:5)\n at .../node_modules/react-router/lib/getComponents.js:28:5\n at .../node_modules/react-router/lib/AsyncUtils.js:54:5\n at Array.forEach (native)"}

We added the History module, but it looks like the react-router use his own dependencies.

It's quite an easy isomorphic router we use;

export default function isomorphicRouter(location, history, store) {
  let routes = createRoutes(store);

  return new Promise((resolve, reject) => {
    match({ routes, location }, (error, redirectLocation, renderProps) => {

      let component;

      if (error) {
        return reject(error);
      }

      if (redirectLocation) {
        return resolve({
          redirectLocation,
          isRedirect: true
        });
      }

      if (history) {
        renderProps.history = history;
      }

      component = (
        <Provider store={store} key="provider">
          {() => <Router {...renderProps} children={routes} />}
        </Provider>
      );

      return resolve({
        component,
        isRedirect: false
      });
    });
  });
}

And we use it in this server.js file;

import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import csrf from 'csurf';
import createStore from './redux/create';
import ApiClient from './api-client';
import createLocation from 'history/lib/createLocation';
import React from 'react';
import Html from './html';
import PrettyError from 'pretty-error';
import isomorphicRouter from './isomorphic-router';
import {API_PORT} from './utils/consts';
import httpProxy from 'http-proxy';

let server = express();
let port = process.env.PORT || 4000;
let env = server.get('env');
let csrfProtection = csrf({
  cookie: true
});
let pretty = new PrettyError();

let proxy = httpProxy.createProxyServer({
  target: 'http://localhost:' + API_PORT
});

proxy.on('error', (error) => {
  log('proxy error', error);
});

server.use('/', express.static(__dirname + '/../build'));
server.use(cookieParser());

// Proxy to the API service gateway.
server.use('/api', (req, res) => {
  proxy.web(req, res);
});

server.use(bodyParser.json());

server.use(csrfProtection, (req, res) => {
  let client = new ApiClient(req);
  let store = createStore(client);
  let location = createLocation(req.url);

  if (IS_SSR_DISABLED) {
    res.send('<!DOCTYPE html>\n' + React.renderToString(<Html component={<div />} store={store} />));
  } else {
    isomorphicRouter(location, undefined, store)
      .then(({component, redirectLocation, isRedirect}) => {
        if (isRedirect) {
          res.redirect(redirectLocation.pathname);

          return;
        }

        res.send('<!DOCTYPE html>\n' + React.renderToString(<Html component={component} store={store} />));
      })
      .catch((error) => {
        if (error.redirect) {
          res.redirect(error.redirect);

          return;
        }

        log('ROUTER ERROR:', pretty.render(error));
        res.status(500).send({
          error: error.stack
        });
      });
  }
});

server.listen(port, () => {
  if (process.send) {
    process.send('online');
  } else {
    log('listening on http://localhost:' + port + ' in ' + env + ' mode');
  }
});

export default server;

It it the let location = createLocation(req.url); who is not initialized correctly? I'm very lost in migrating the new changes. Thank you for your help!

Most helpful comment

I recently ran into the same issue during migration.
It wasn't caused by any missing modules or dependencies, but because of the deprecation of pushState.

Previously we'd write the programmatic route changes like this:

History.pushState(null, '/path');

Now they have to done as:

History.push('/path');

A poorly formed href string (or the lack of) in the push method causes this error to be thrown.
After some refactoring the error seems to have gone away.

All 21 comments

Does anyone know what cause this? I'm very lost right now

I would dig into node_modules and add logs at all the locations in that stack trace to figure out why location is null in the useQueries module. Hard to tell if it's a problem with your code or a bug.

Happens to me too (node v4.1.1) It seems like the history module which react-router depends on doesn't install its own dependencies. It does fine when it's installed separately.

Addendum: this is only the case for react-router v1.0.0-rc2. rc1 works.

The history module is installed separately in my project and i'm on rc1. I just can't where the actual problem occurs in the code and why. What's the best way to log traces in a module?

Getting this as well when upgrading from v1.0.0-rc1.

I just updated to v1.0.0-rc2 and also getting this error. I also installed the history module separately.

v1.0.0-rc3 solves this problem.

Got this error instead
error: "TypeError: Cannot read property 'query' of null at addQuery (/Users/mboutin2/working-directory/crakrevenue-phoenix/node_modules/react-router/node_modules/history/lib/useQueries.js:46:19) at /Users/mboutin2/working-directory/crakrevenue-phoenix/node_modules/react-router/node_modules/history/lib/useQueries.js:67:18 at /Users/mboutin2/working-directory/crakrevenue-phoenix/node_modules/react-router/lib/useRoutes.js:272:15 at /Users/mboutin2/working-directory/crakrevenue-phoenix/node_modules/react-router/lib/useRoutes.js:120:15 at done (/Users/mboutin2/working-directory/crakrevenue-phoenix/node_modules/react-router/lib/AsyncUtils.js:49:19) at /Users/mboutin2/working-directory/crakrevenue-phoenix/node_modules/react-router/lib/AsyncUtils.js:55:7 at getComponentsForRoute (/Users/mboutin2/working-directory/crakrevenue-phoenix/node_modules/react-router/lib/getComponents.js:9:5) at /Users/mboutin2/working-directory/crakrevenue-phoenix/node_modules/react-router/lib/getComponents.js:28:5 at /Users/mboutin2/working-directory/crakrevenue-phoenix/node_modules/react-router/lib/AsyncUtils.js:54:5 at Array.forEach (native)" }

[fixed]

I have history module installed separately.

I'm getting this error with RC3:

function addQuery(location) {
          if (location.query == null) 

TypeError: Cannot read property 'query' of null

I was having the error because of using <Route history={history} ... before match() on the server.
I fixed the error by removing the history attribute from the root Route and by moving history to rendered_props in

routes = <Route ...>...</Route>

match({ routes, history, location }, (error, redirect_location, render_props) =>
{
            // used only on client for <Router history={history} ...>
            if (history)
            {
                render_props.history = history
            }

            React.createElement(Router, render_props)
}

v1.0.0-rc3 doesn't solve the problem :S

This is caused by a disconnect between the internal history lib dependency in react-router and your app history lib dependency version. I would imagine it should work if the versions match.

I don't have history installed as a dependency (only as a sub-dependency) and i'm still getting:
Cannot read property 'apply' of undefined
when a user visits a url with an onEnterHook. I'm also using redux-router but i'm struggling to find out what's up... @aackerman

Edit: In my case it seems to be an inconsistency between my react-router (rc3) and redux-router's (rc1). So.. i think i get it now..

Hi.

I have also this error with

TypeError: Cannot read property 'query' of undefined

I am using react-router on server side and I have checked all examples here and somewhere else and it seems i am getting this error with query. Is there any solution to this problem?

server.js

app.get('*', function(req, res) {
    // Note that req.url here should be the full URL path from
    // the original request, including the query string.
    var location = createLocation(req.url);

    match({routes, location: location}, function(error, redirectLocation, renderProps) {

        // used only on client for <Router history={history} ...>
        if (history) {
            renderProps.history = history;
        }

        if (error) {
            res.status(500).send(error.message);
        } else if (redirectLocation) {
            res.redirect(302, redirectLocation.pathname + redirectLocation.search);
        } else if (renderProps) {
            var RoutingContextFactory = React.createFactory(RoutingContext, renderProps);
            res.status(200).render('index.ejs', { reactOutput: ReactDOMServer.renderToString(RoutingContextFactory()) });
        } else {
            res.status(404).send('Not found');
        }
    });
});
routes.js


var createLocation = require('history').createLocation;
var useBasename = require('history').useBasename;

var history = useBasename(createLocation)({
    basename: '/'
});

module.exports = [
    <Router history={history}>
        <Route path="/" component={App}>
            <Route path="login" component={Login} />
            <Route path="logout" component={Logout} />
            <Route path="review" component={ReviewHandler} onEnter={requireAuth} />
        </Route>
    </Router>
];

I am having this exact issue as everyone else. Any real fix for this?

same issue here :/

I recently ran into the same issue during migration.
It wasn't caused by any missing modules or dependencies, but because of the deprecation of pushState.

Previously we'd write the programmatic route changes like this:

History.pushState(null, '/path');

Now they have to done as:

History.push('/path');

A poorly formed href string (or the lack of) in the push method causes this error to be thrown.
After some refactoring the error seems to have gone away.

I was having the same issue and figured out that the link I was creating had an invalid to property.

var permalink = null
<Link to={ permalink }>This will throw "Cannot read property 'query' of null"</Link>

IMHO, react-router should consider "" as default if to is falsy.

Same error while trying to run Telescope. I didn't enter my own code. It was just a fresh install of Telescope. It first asked me to install [email protected] a as a dependency and I did meteor npm install --save [email protected]

The app worked fine a couple of times. I created a user and a post. And now I am getting this error. If the issue is related to the version of react-router not matching with whatever package requires it, what version should I install. Below is the error I am getting:

W20160728-11:41:45.801(3)? (STDERR) Thu Jul 28 2016 11:41:45 GMT+0300 (EAT) 'error while server-rendering' 'TypeError: Cannot read property \'query\' of undefined\n at CategoriesList.render (packages/nova:base-components/lib/categories/CategoriesList.jsx:83:34)\n at [object Object].ReactCompositeComponentMixin._renderValidatedComponentWithoutOwnerOrContext (/Users/merhawi/Documents/hubs/codehub/meteor/Telescope/node_modules/react/lib/ReactCompositeComponent.js:687:34)\n at [object Object].ReactCompositeComponentMixin._renderValidatedComponent (/Users/merhawi/Documents/hubs/codehub/meteor/Telescope/node_modules/react/lib/ReactCompositeComponent.js:707:32)\n at [object Object].wrapper [as _renderValidatedComponent] (/Users/merhawi/Documents/hubs/codehub/meteor/Telescope/node_modules/react/lib/ReactPerf.js:66:21)\n at [object Object].ReactCompositeComponentMixin.performInitialMount (/Users/merhawi/Documents/hubs/codehub/meteor/Telescope/node_modules/react/lib/ReactCompositeComponent.js:291:30)\n at [object Object].ReactCompositeComponentMixin.mountComponent (/Users/merhawi/Documents/hubs/codehub/meteor/Telescope/node_modules/react/lib/ReactCompositeComponent.js:222:21)\n at [object Object].wrapper [as mountComponent] (/Users/merhawi/Documents/hubs/codehub/meteor/Telescope/node_modules/react/lib/ReactPerf.js:66:21)\n at Object.ReactReconciler.mountComponent (/Users/merhawi/Documents/hubs/codehub/meteor/Telescope/node_modules/react/lib/ReactReconciler.js:39:35)\n at [object Object].ReactCompositeComponentMixin.performInitialMount (/Users/merhawi/Documents/hubs/codehub/meteor/Telescope/node_modules/react/lib/ReactCompositeComponent.js:297:34)\n at [object Object].ReactCompositeComponentMixin.mountComponent (/Users/merhawi/Documents/hubs/codehub/meteor/Telescope/node_modules/react/lib/ReactCompositeComponent.js:222:21)'

Same error for me, it was also the Link having an invalid 'To' property.

<li><Link to={ s.slug }>{ s.title }</Link></li>

In this case s.slug was undefined. Could improve the error?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

davetgreen picture davetgreen  路  3Comments

ArthurRougier picture ArthurRougier  路  3Comments

hgezim picture hgezim  路  3Comments

jzimmek picture jzimmek  路  3Comments

wzup picture wzup  路  3Comments