Thiopurine therapy is a cornerstone in the treatment of inflammatory bowel disease (IBD). We aimed to assess the effect of thiopurines on cancer risk in IBD according to drug exposure and age. Danish national registers were used to identify incident IBD patients, exposure to drugs and status of cancers, in 1996-2018. Cox regressions were used to compare cancer risks in IBD and non-IBD individuals and to assess IBD patients' cumulative drug exposure and the association to first cancer, excluding non-melanoma skin cancer. We followed 43,419 IBD patients for a median of 8.2 years (IQR:3.7-14.2) after IBD diagnosis. Cancer was reported in 3,128 (7.2%) IBD patients. The risk of cancer was increased in IBD patients in all age categories compared to non-IBD individuals (<50 years (aHR: 1.59 (95%CI: 1.43-1.77)), 50-65 years (aHR: 1.31 (95%CI: (1.19-1.44)), and >65 years (aHR: 1.14 (95%CI: 1.05-1.24)). Monotherapy and combination therapy were associated with cancer (aHR:1.36 (95%CI:1.17-1.57) and (aHR:2.49 (95%CI:1.64-3.78), respectively) compared to unexposed IBD patients. Among elderly (>65 years), the aHR was 2.79 (95%CI:1.24-6.28) in those receiving combination therapy. In patients discontinuing thiopurines, aHRs returned to the level of unexposed (aHR:0.89 (95%CI:0.78-1.01)). The aHR was positively associated with cumulative thiopurine exposure and in patients with >5 years of exposure, reaching aHR 1.36 (95%CI:1.15-1.61). Thiopurines were associated with increased hazard of cancer, especially when used in combination therapy in the elderly. The hazard increased by 36% when patients were exposed to thiopurines for more than five years. Reassuringly, the hazard returned to baseline after discontinuation of thiopurines.