Planetary systems are born in the disks of gas, dust and rocky fragments that surround newly formed stars. Solid content assembles into ever-larger rocky fragments that eventually become planetary embryos. These then continue their growth by accreting leftover material in the disk. Concurrently, tidal effects in the disk cause a radial drift in the embryo orbits, a process known as migration. Fast inward migration is predicted by theory for embryos smaller than three to five Earth masses. With only inward migration, these embryos can only rarely become giant planets located at Earth's distance from the Sun and beyond, in contrast with observations. Here we report that asymmetries in the temperature rise associated with accreting infalling material produce a force (which gives rise to an effect that we call 'heating torque') that counteracts inward migration. This provides a channel for the formation of giant planets and also explains the strong planet-metallicity correlation found between the incidence of giant planets and the heavy-element abundance of the host stars.