The merger of two neutron stars is predicted to give rise to three major detectable phenomena: a short burst of γ-rays, a gravitational-wave signal, and a transient optical-near-infrared source powered by the synthesis of large amounts of very heavy elements via rapid neutron capture (the r-process). Such transients, named 'macronovae' or 'kilonovae', are believed to be centres of production of rare elements such as gold and platinum. The most compelling evidence so far for a kilonova was a very faint near-infrared rebrightening in the afterglow of a short γ-ray burst at redshift z = 0.356, although findings indicating bluer events have been reported. Here we report the spectral identification and describe the physical properties of a bright kilonova associated with the gravitational-wave source GW170817 and γ-ray burst GRB 170817A associated with a galaxy at a distance of 40 megaparsecs from Earth. Using a series of spectra from ground-based observatories covering the wavelength range from the ultraviolet to the near-infrared, we find that the kilonova is characterized by rapidly expanding ejecta with spectral features similar to those predicted by current models. The ejecta is optically thick early on, with a velocity of about 0.2 times light speed, and reaches a radius of about 50 astronomical units in only 1.5 days. As the ejecta expands, broad absorption-like lines appear on the spectral continuum, indicating atomic species produced by nucleosynthesis that occurs in the post-merger fast-moving dynamical ejecta and in two slower (0.05 times light speed) wind regions. Comparison with spectral models suggests that the merger ejected 0.03 to 0.05 solar masses of material, including high-opacity lanthanides.