Infections, which can prompt neuroinflammation, may be a risk factor for dementia1–5. More information is needed concerning associations across different infections and different dementias, and from longitudinal studies with long follow-ups. This New Zealand-based population register study tested whether infections antedate dementia across three decades. We identified individuals born between 1929 and 1968 and followed them from 1989 to 2019 (n = 1,742,406, baseline age = 21–60 years). Infection diagnoses were ascertained from public hospital records. Dementia diagnoses were ascertained from public hospital, mortality and pharmaceutical records. Relative to individuals without an infection, those with an infection were at increased risk of dementia (hazard ratio 2.93, 95% confidence interval 2.68–3.20). Associations were evident for dementia diagnoses made up to 25–30 years after infection diagnoses. Associations held after accounting for preexisting physical diseases, mental disorders and socioeconomic deprivation. Associations were evident for viral, bacterial, parasitic and other infections, and for Alzheimer's disease and other dementias, including vascular dementia. Preventing infections might reduce the burden of neurodegenerative conditions. In this nationwide administrative register study, individuals diagnosed with infections were three times more likely to be diagnosed with dementia up to 30 years later. Preventing infections might reduce the burden of neurodegenerative conditions.