Gamma-ray bursts (GRBs) are among the most energetic events in the universe and can be detected up to very high redshift. They are therefore a unique tool to probe the distant universe and cosmic evolution. The fading nature of GRBs and the fact that their afterglows can be very bright make GRBs ideal background sources to probe the gas along their lines of sight. Moreover, the identification of GRB host galaxies allow the building of a sample of faint star forming galaxies, not selected by luminosity criteria, that would be hardly detected by conventional surveys. In this seminar I will show which kind of information can be obtained on the GRB host galaxies and on the foreground systems using the GRB afterglow optical and near-infrared spectra. In particular I will present some recent results on the statistics and characteristics of the intervening MgII systems present along GRB lines of sight.