Factors like your well-being, ability to plan and discipline to stay away from distractions play a major role in our ability to concentrate. Approaching each coding session with the right attitude and with a plan will also go a long way in helping to keep your alertness.
Project management tools, time management techniques and even music can also assist in improving your productivity and keep you focused while coding.