Carbon dioxide (CO2) is a key chemical species that is found in a wide range of planetary atmospheres. In the context of exoplanets, CO2 is an indicator of the metal enrichment (that is, elements heavier than helium, also called 'metallicity')1-3, and thus the formation processes of the primary atmospheres of hot gas giants4-6. It is also one of the most promising species to detect in the secondary atmospheres of terrestrial exoplanets7-9. Previous photometric measurements of transiting planets with the Spitzer Space Telescope have given hints of the presence of CO2, but have not yielded definitive detections owing to the lack of unambiguous spectroscopic identification10-12. Here we present the detection of CO2 in the atmosphere of the gas giant exoplanet WASP-39b from transmission spectroscopy observations obtained with JWST as part of the Early Release Science programme13,14. The data used in this study span 3.0-5.5 micrometres in wavelength and show a prominent CO2 absorption feature at 4.3 micrometres (26-sigma significance). The overall spectrum is well matched by one-dimensional, ten-times solar metallicity models that assume radiative-convective-thermochemical equilibrium and have moderate cloud opacity. These models predict that the atmosphere should have water, carbon monoxide and hydrogen sulfide in addition to CO2, but little methane. Furthermore, we also tentatively detect a small absorption feature near 4.0 micrometres that is not reproduced by these models.