In the local universe, galaxies in clusters typically show different physical and chemical properties compared to more isolated systems. Understanding how this difference originates, and whether it is already in place at high redshift, is still a matter of debate. Thanks to uniquely deep optical spectra available from the VANDELS survey, we investigate environmental effects on the stellar mass–metallicity relation (MZR) for a sample of nearly 1000 star-forming galaxies in the redshift range 2 < z < 4. We complement our dataset with the MOSFIRE follow-up of 21 galaxies to study the environmental dependence of the gas-phase MZR. Robust stellar and gas-phase metallicities are derived from well-calibrated photospheric absorptions features, respectively at 1501 and 1719 Å in the stacked spectra, and from optical emission lines ([OII]λλ3726−3729, [OIII]λ5007, and Hβ) in individual systems. We characterize the environment through multiple criteria by using the local galaxy density maps derived in the VANDELS fields to identify overdense structures and protoclusters of varying sizes. We find that environmental effects are weak at redshifts 2 < z < 4, and they are more important around the densest overdensity structures and protoclusters, where galaxies have a lower stellar metallicity (by ∼0.2 dex) and a lower gas-phase metallicity (by 0.1 dex) compared to the field, with a significance of 1σ and 2σ, respectively. Crucially, this downward offset cannot be explained by a selection effect due to a higher star formation rate, a fainter UV continuum, or different dust attenuations and stellar ages for galaxies in overdense enviroments with respect to the field. In spite of the still low signal-to-noise ratio of our results, we consider possible explanations of this environmental dependence. We propose a combination of increased mergers and high-speed encounters, more efficient AGN feedback in dense cores, and cold gas inflows from the cosmic web as viable physical mechanisms diluting the metal content of the cold gas reservoirs of overdense galaxies or expelling their metals to the intergalactic medium, even though additional studies are needed to determine the most significant scenario. Finally, some tensions remain between observations and both semi-analytic models and hydrodynamical simulations, which predict no significant metallicity offset as a function of host halo mass, suggesting that an explicit implementation of environmental processes in dense protocluster cores is needed.