For almost a quarter of a century$^1$, 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 bursts$^3$ are explained naturally if they lie at cosmological distances (a few Gpc)$^4$, but there is a countervailing view that they are relatively local objects$^5$, 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 burst$^6,7$. The optical transient appears to be associated with a faint galaxy$^7,8$, suggesting that the burst occurred in that galaxy and thus that γ-ray bursts in general lie at cosmological distance.