Bach wrote music for the purpose of glorifying God, and to use his talent bestowed upon him by his Creator for HIS glory.
As to dedicating his music to God - he did. On his blank manuscript paper, he would often write "J.J" - "Jesu Juva" ("Help me, Jesus"), and upon finished works "I.N.J" -In Nomine Jesu ("In the Name of Jesus"), or "Soli Deo Gloria" - To God Alone Be the Glory.
Bach wrote of 1 Cron. 25 - "The chapter is the true foundation for all God-pleasing music", and wrote that "Where there is devotional music, God is always at hand with His gracious presence". He realized the he was only a recipient of God's grace with his giftedness and musical talent - and he sought to secure the reality of this in the minds of his audiences.
Bach is only one of the many composers that realized this, however...study the life of Handel, Haydn (after his last performance, hands lifter toward heaven said "Not from me - from there, from above, comes everything"), Beethoven ("Almighty God, You look down into my innermost soul, You see into my heart and You know that it is filled with love for humanity and a desire to do good."), Schubert ("Man comes into the world with faith, which is far superior to knowledge and understanding, for to understand a thing one must first of all believe in it. Reason is nothing more that analyized belief"), Mendlelssohn, and many others.
I highly recommend "Spiritual Lives of Great Composers" by Patrick Kavanaugh, if you want to know more...excellent read.
Sarah