For almost a quarter of a century1, the origin of γ-ray bursts- brief, energetic bursts of high-energy photons-has remained unknown. The detection of a counterpart at another wavelength has long been thought to be a key to understanding the nature of these bursts (see, for example, ref. 2), but intensive searches have not revealed such a counterpart. The distribution and properties of the bursts3 are explained naturally if they lie at cosmological distances (a few Gpc)4, but there is a countervailing view that they are relatively local objects5, perhaps distributed in a very large halo around our Galaxy. Here we report the detection of a transient and fading optical source in the error box associated with the burst GRB970228, less than 21 hours after the burst6,7. The optical transient appears to be associated with a faint galaxy7,8, suggesting that the burst occurred in that galaxy and thus that γ-ray bursts in general lie at cosmological distance.