Start by peeling the potatoes (optional) and slicing them evenly to about ⅛ to ¼-inch thick.
For the cheese sauce, melt the butter in a saucepan over medium heat. Add the chopped onions and cook for 3 minutes, until softened. Stir in the garlic and thyme and cook for an additional minute. Sprinkle in the flour and stir to combine. Slowly pour in the heavy cream, stirring constantly. Add salt, pepper, thyme, and cayenne (if using). Stir in 2 cups of shredded cheddar cheese and cook until melted and smooth. Remove the sauce from the heat.
Next, preheat the oven to 375°F (190°C) and grease a baking dish. Layer half of the sliced potatoes at the bottom of the dish. Pour half of the cheese sauce over the potatoes and sprinkle ½ of the remaining shredded cheese on top. Repeat the layers with the remaining potatoes, cheese sauce, and cheese. Garnish with chopped chives, thyme, or parsley if desired.
Cover the dish with foil and bake for 40 minutes. Remove the foil, sprinkle the remaining cheese on top, and bake for another 20 minutes, until golden brown and bubbly. Let the dish cool for a few minutes before serving. Garnish with additional chives, parsley, or thyme.