A long-standing paradigm in astrophysics is that collisions—or mergers—of two neutron stars form highly relativistic and collimated outflows (jets) that power γ-ray bursts of short (less than two seconds) duration. The observational support for this model, however, is only indirect. A hitherto outstanding prediction is that gravitational-wave events from such mergers should be associated with γ-ray bursts, and that a majority of these bursts should be seen off-axis, that is, they should point away from Earth. Here we report the discovery observations of the X-ray counterpart associated with the gravitational-wave event GW170817. Although the electromagnetic counterpart at optical and infrared frequencies is dominated by the radioactive glow (known as a ‘kilonova’) from freshly synthesized rapid neutron capture (r-process) material in the merger ejecta, observations at X-ray and, later, radio frequencies are consistent with a short γ-ray burst viewed off-axis. Our detection of X-ray emission at a location coincident with the kilonova transient provides the missing observational link between short γ-ray bursts and gravitational waves from neutron-star mergers, and gives independent confirmation of the collimated nature of the γ-ray-burst emission.