01 - Preheat oven to 375°F. Generously grease a 9x13-inch baking dish with butter or cooking spray.
02 - Melt 2 tablespoons butter in a large skillet over medium heat. Add sliced onions and a pinch of salt. Cook, stirring frequently, until deeply golden and caramelized, about 20-25 minutes. Add minced garlic during the last minute and remove from heat.
03 - Combine heavy cream, whole milk, dried thyme, nutmeg, black pepper, and remaining 1 tablespoon butter in a small saucepan. Heat over medium-low until steaming, whisking occasionally. If using flour, whisk in until smooth and slightly thickened. Do not boil.
04 - Arrange half of the sweet potato slices in the prepared baking dish, overlapping slightly. Season lightly with salt. Spread half of the caramelized onions over the potatoes, then sprinkle with half of the Gruyère and cheddar cheeses.
05 - Repeat with remaining sweet potatoes, caramelized onions, and cheeses, creating another complete layer.
06 - Pour the warm cream mixture evenly over the entire dish, ensuring it reaches all corners. Cover tightly with aluminum foil.
07 - Bake covered for 40 minutes, allowing potatoes to steam and soften in the cream.
08 - Remove foil and continue baking uncovered for 20 additional minutes, or until the top is golden brown and bubbly, and potatoes are fork-tender.
09 - Let the gratin rest for 10 minutes before serving to allow the sauce to thicken slightly. Garnish with fresh chives if desired.