The cognitive reserve hypothesis posits that cognitively stimulating work delays the onset of mild cognitive impairment (MCI) and dementia. However, the effect of occupational cognitive demands across midlife on the risk of these conditions is unclear. Using a cohort study design, we evaluated the association between registry-based trajectories of occupational cognitive demands from ages 30-65 years and clinically diagnosed MCI and dementia in participants in the HUNT4 70+ Study (2017-19). Group-based trajectory modeling identified trajectories of occupational cognitive demands, measured by the routine task intensity (RTI) index (lower RTI indicates more cognitively demanding occupation) from the Occupational Information Network. Multinomial regression was implemented to estimate the relative risk ratios (RRRs) of MCI and dementia, after adjusting for age, sex, education, income, baseline hypertension, obesity, diabetes, psychiatric impairment, hearing impairment, loneliness, smoking status, and physical inactivity assessed at HUNT1-2 in 1984-1986 and 1995-1997. To handle missing data, we used inverse probability weighting to account for nonparticipation in cognitive testing and multiple imputation. Based on longitudinal RTI scores for 305 unique occupations, 4 RTI trajectory groups were identified (n = 7,003, 49.8% women, age range 69-104 years): low RTI (n = 1,431, 20.4%), intermediate-low RTI (n = 1,578, 22.5%), intermediate-high RTI (n = 2,601, 37.1%), and high RTI (n = 1,393, 19.9%). Participants in the high RTI group had a higher risk of MCI (RRR 1.74, 95% CI 1.41-2.14) and dementia (RRR 1.37, 95% CI 1.01-1.86), after adjusting for age, sex, and education compared with participants in the low RTI group. In a sensitivity analysis, controlling for income and baseline health-related factors, the point estimates were not appreciably changed (RRR 1.66, 95% CI 1.35-2.06 for MCI, and RRR 1.31, 95% CI 0.96-1.78 for dementia). People with a history of cognitively stimulating occupations during their 30s, 40s, 50s, and 60s had a lower risk of MCI and dementia older than 70 years, highlighting the importance of occupational cognitive stimulation during midlife for maintaining cognitive function in old age. Further research is required to pinpoint the specific occupational cognitive demands that are most advantageous for maintaining later-life cognitive function.