To avoid overcooking, cook the spaghetti until it's al dente. This usually takes 4-6 minutes. It ensures the spaghetti retains a slight bite during baking.