Background Spontaneous abortion has been associated with higher risk of type 2 diabetes mellitus (T2DM) and gestational diabetes mellitus (GDM), while the evidence remains equivocal. This study aimed to examine the association between spontaneous abortion and the risk of T2DM and GDM, and assesses whether lifestyle factors modified this association. Methods This cross-sectional study used data from the UK Biobank, recruiting 170 599 ever-pregnant women from 22 assessment centers in England, Scotland, and Wales between 2006 and 2010. History of spontaneous abortion was self-reported and was confirmed by using medical records, categorized as none, 1, 2, or >= 3 spontaneous abortions. The primary outcomes, T2DM and GDM, were ascertained from medical records using ICD-10 codes. Multivariable logistic regression was performed to estimate the adjusted odds ratios (ORs) and 95% confidence intervals (CIs), adjusting for sociodemographic and health factors (e.g., age, ethnicity, cancer, chronic hypertension), reproductive factors (e.g., use of oral contraceptives, use of hormone treatment, hypertensive disorders of pregnancy), and lifestyle score. The lifestyle score was constructed based on smoking status, alcohol intake, physical activity, television viewing time, sleep duration, and diet quality. Effect modification by lifestyle score was assessed using multiplicative interaction terms in the regression models. Results Among 170 599 ever-pregnant women (mean [SD] age, 56.4 [8.0] years), a history of spontaneous abortion was associated with higher odds of T2DM (OR 1.17, 95% CI 1.10-1.24) and GDM (OR 1.38, 95% CI 1.20-1.60). The odds were higher for recurrent spontaneous abortions (for T2DM: ORs were 1.33 [95% CI 1.14-1.56] for three or more spontaneous abortions, 1.07 [95% CI 0.93-1.23] for two, and 1.09 [95% CI 1.01-1.17] for one compared with none; for GDM: the corresponding ORs were 2.01 [95% CI 1.48-2.71], 1.21 [95% CI 0.90-1.64], and 1.20 [95% CI 1.01-1.42], respectively). The odds of T2DM and GDM higher with less healthy lifestyle behaviors in both categories of spontaneous abortion, although no significant interactions between spontaneous abortion and lifestyle score were observed (P-interaction>0.05). Conclusions Spontaneous abortion was associated with higher odds of T2DM and GDM, with a stronger association observed in women who experienced recurrent spontaneous abortions. It is imperative to integrate reproductive history into routine diabetes risk assessment, particularly for women with a history of multiple spontaneous abortions.