The merger of two neutron stars is predicted to give rise to three major detectable phenomena: a short burst of gamma-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)(1-3). Such transients, named 'macronovae' or 'kilonovae'(4-7), are believed to be centres of production of rare elements such as gold and platinum(8). The most compelling evidence so far for a kilonova was a very faint near-infrared rebrightening in the afterglow of a short gamma-ray burst(9,10) at redshift z = 0.356, although findings indicating bluer events have been reported(11). Here we report the spectral identification and describe the physical properties of a bright kilonova associated with the gravitational-wave source(12) GW170817 and gamma-ray burst(13,14) 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(15,16). 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.