Get current node id from controller I am building a module with reactjs and I need to get the current node id from a controller so I can do certain tasks based on the node id but I always receive a null value, my routing is working correctly and my function is the following: 

  public function currentNodeId()
    {
        // get current node
        $node_id = \Drupal::routeMatch()-&gt;getParameter('node')-&gt;Id();

        return new JsonResponse(
            array(
                'node_id' =&gt; $node_id
            )
        );
    }


and in mymodule.routing.yml I have:

 mymodule-currentNode:
   path: '/mymodule/currentNodeId'
   defaults:
     _controller: '\Drupal\mymodule\Controller\MyModuleController::currentNodeId'
     _title: 'Current node id'
   requirements:
     _permission: 'access content'


I can get the current node id from my module file 'mymodule.module' doing the same I did in the currentNodeId function:

   $node_id = \Drupal::routeMatch()-&gt;getParameter('node')-&gt;Id();


Anyone knows if this is some kind of security or am I doing anything wrong? Thank you

EDIT

This is what I have in my js file, I do this call and I want to get the current node id so then I can do a certain task, in the console I get null or undefined every time I do the request

$.get('/mymodule/currentNodeId/', function (data) {
                        console.log(data.node_id);
                    });
Your route has no node parameter. See the documentation Structure of routes and the example from there:

book.export:
  # This path takes dynamic arguments, which are enclosed in { }.
  path: '/book/export/{type}/{node}'
  defaults:
    # Because this route does not return HTML, use _controller.
    _controller: '\Drupal\book\Controller\BookController::bookExport'
  requirements:
    _permission: 'access printer-friendly version'
    # Ensure user has access to view the node passed in.
    _entity_access: 'node.view'


You can access the route parameters in the controller directly in the function arguments:

public function bookExport($type, NodeInterface $node) {
  // get the id from the controller argument
  $node_id = $node-&gt;id();
}


\Drupal::routeMatch()-&gt;getParameter() is to get a route parameter outside of the controller, for example in a preprocess hook. For this to work the parameter has to be defined in the current route as well.