01 -
Preheat the oven to 350°F (175°C). Lightly butter a 9x13-inch baking dish and set aside.
02 -
Place chopped bacon in a large skillet over medium heat. Cook, stirring occasionally, until evenly crisp, 6 to 8 minutes. Transfer bacon to a paper towel-lined plate. Reserve 2 tablespoons bacon fat in skillet.
03 -
Add sliced onions to the reserved bacon fat in the skillet. Cook over medium-low heat, stirring occasionally, until golden brown and caramelized, 30 to 40 minutes. If onions begin to stick, add a splash of water to loosen from pan.
04 -
Melt butter in a saucepan over medium heat. Add flour and cook, whisking constantly, until pale and bubbly, about 2 minutes. Gradually whisk in milk and cream, ensuring no lumps remain. Continue whisking until thickened, 5 to 7 minutes.
05 -
Stir in 3/4 teaspoon salt, 1/2 teaspoon black pepper, and cayenne pepper if using. Remove from heat. Add half of the Gruyère and half of the cheddar cheese, whisk until fully melted and smooth.
06 -
Arrange half of the potato slices in an even, overlapping layer in the prepared dish. Scatter half the caramelized onions, half the bacon, and a sprinkle each of salt and pepper over the potatoes. Pour half the sauce evenly over the layer. Repeat layering with remaining potatoes, onions, bacon, and sauce. Top evenly with remaining cheeses.
07 -
Cover the dish tightly with foil and bake for 50 minutes. Remove foil and continue baking until the top is deeply golden, bubbling, and potatoes are tender, 25 to 35 minutes more.
08 -
Allow casserole to rest at least 15 minutes before serving. Garnish with fresh thyme leaves if desired.