
How to Get Sunrise and Sunset Times in JavaScript (Free API)
I needed sunrise and sunset times for a few of my own sites, and every option I found either wanted an API key or made me do the astronomy and timezone math myself. So I built SunriseSunset.io, a free sunrise and sunset API. No key, no signup, and it works straight from the browser.
Full disclosure: it’s my API, so I’m biased. But it’s free, and the examples below work as written.
In this post, I’ll show you how to get sunrise and sunset times in JavaScript, show them in the right timezone, pull a whole year of dates in one request, and handle the errors and edge cases that trip people up.
Let’s get into it.
Quick Start: Sunset Time in 5 Lines
Since you’re likely here for the code, here’s the shortest working version. It runs in the browser console or in Node 18+ (save it as sunset.mjs and run node sunset.mjs):
const lat = 38.6245;
const lng = -90.1858;
const res = await fetch(`https://api.sunrisesunset.io/json?lat=${lat}&lng=${lng}`);
const { results } = await res.json();
console.log(`Sunrise: ${results.sunrise}`);
console.log(`Sunset: ${results.sunset}`);
Output for the Gateway Arch in St. Louis on November 21, 2026:
Sunrise: 6:47:15 AM
Sunset: 4:45:45 PM
That’s it. Times come back in the local timezone of the coordinates you pass, so you don’t need to know the timezone ahead of time.
You can get coordinates for any place by right-clicking it on Google Maps and copying the lat/lng.

The Sunrise Sunset API at a Glance
Everything is one GET request:
https://api.sunrisesunset.io/json?lat=38.907192&lng=-77.036873
- Cost: free for personal and commercial use, with a required link back (more on that below).
- Auth: none. No API key, no signup.
- CORS: enabled, so you can call it from any web page without a backend.
- Date ranges: up to 365 days per request.
- Rate limits: none enforced, within reason. Cache on your end if you’d be calling it hourly per user.
One thing worth knowing about keys: the API doesn’t check them yet. If your app depends on it, you can create a key and send it anyway, so your requests keep working if keyless traffic ever needs limits. Send it as a header, never in the URL, since proxies and CDNs log query strings:
Authorization: Bearer sss_...
A Reusable Fetch Function With Error Handling
The quick start skips error handling. For real code, use something like this. It works the same in the browser and Node:
async function getSunTimes(lat, lng, params = {}) {
const query = new URLSearchParams({ lat, lng, ...params });
const res = await fetch(`https://api.sunrisesunset.io/json?${query}`);
const data = await res.json().catch(() => ({
status: `HTTP_${res.status}`,
error: 'Response was not JSON',
}));
// INVALID_TZID still returns good data in the location's own timezone
if (data.status !== 'OK' && data.status !== 'INVALID_TZID') {
throw new Error(`${data.status}: ${data.error}`);
}
return data.results;
}
Every response has a status field. On an error, results is null and you get an error message instead:
try {
await getSunTimes(38.6245, -90.1858, { date: '2026-02-30' });
} catch (err) {
console.error(err.message);
}
INVALID_DATE: Invalid date format provided.
Here are all the status values:
OK: the request worked.INVALID_REQUEST: missing or malformedlat/lng(HTTP 400).INVALID_DATE: a date it can’t parse, or a range longer than one year (HTTP 400).INVALID_TZID: thetimezoneyou passed didn’t validate. This one still returns full data on a 200, using the location’s own timezone, so don’t treat it as a failure.UNKNOWN_ERROR: something broke on the server. Retry.
The .catch() on res.json() is there because if something between you and the API fails (a proxy, a timeout, a 503 page), the body might not be JSON at all. This way you still get a readable error instead of a SyntaxError.
fetch itself throws a TypeError when the network is down, and that goes straight to your catch too.
The rest of the examples in this post use getSunTimes().
Show the Sunset Time on a Web Page
Here’s a complete HTML page that asks for the visitor’s location and shows their sunset time. Copy it into a file and open it in a browser:
<p id="sunset">Loading sunset time...</p>
<p>Powered by <a href="https://sunrisesunset.io">SunriseSunset.io</a></p>
<script type="module">
async function getSunTimes(lat, lng, params = {}) {
const query = new URLSearchParams({ lat, lng, ...params });
const res = await fetch(`https://api.sunrisesunset.io/json?${query}`);
const data = await res.json().catch(() => ({
status: `HTTP_${res.status}`,
error: 'Response was not JSON',
}));
if (data.status !== 'OK' && data.status !== 'INVALID_TZID') {
throw new Error(`${data.status}: ${data.error}`);
}
return data.results;
}
function getPosition() {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject, { timeout: 10000 });
});
}
async function showSunset() {
const output = document.querySelector('#sunset');
try {
const { coords } = await getPosition();
const sun = await getSunTimes(coords.latitude, coords.longitude);
output.textContent = `Sunset today: ${sun.sunset}`;
} catch (err) {
output.textContent = "Couldn't load sunset time.";
console.error(err);
}
}
showSunset();
</script>
One thing to know upfront: browsers only allow geolocation on HTTPS pages (and localhost), and the visitor has to say yes. If they say no, the catch shows the fallback message. If you already know the location (a store page, a campground listing), skip getPosition() and pass fixed coordinates.
There’s also an older example on CodePen that renders the data to the page.
Format Times in Any Timezone
By default you get display strings like "4:45:45 PM" in the location’s timezone. That’s perfect if you just want to print the time.
If you need to do math with the times, or show them in the viewer’s timezone instead of the location’s, pass formatted=0. You get ISO 8601 strings with the UTC offset included, which new Date() parses correctly:
const sun = await getSunTimes(38.6245, -90.1858, { date: '2026-12-21', formatted: 0 });
const sunset = new Date(sun.sunset);
const fmt = (timeZone) =>
sunset.toLocaleTimeString('en-US', {
timeZone,
hour: 'numeric',
minute: '2-digit',
timeZoneName: 'short',
});
console.log(sun.sunset); // raw ISO string
console.log(fmt(sun.timezone)); // time at the location
console.log(fmt('America/Los_Angeles')); // time for a viewer in LA
console.log(fmt(Intl.DateTimeFormat().resolvedOptions().timeZone)); // viewer's own zone
2026-12-21T16:45:12-06:00
4:45 PM CST
2:45 PM PST
4:45 PM CST
The last line depends on where the code runs. I ran it on Chicago time, so it matched the location. Run it with TZ=Europe/London and it prints 10:45 PM GMT+0.
If you’d rather have the API do the conversion, pass any IANA timezone name with timezone:
const sun = await getSunTimes(38.6245, -90.1858, {
date: '2026-12-21',
timezone: 'Europe/London',
});
console.log(sun.sunset, sun.timezone);
10:45:12 PM Europe/London
Other format options:
time_format=24gives16:45:12.time_format=militarygives military time.time_format=unixgives UTC timestamps in seconds. They come back as strings, so wrap them inNumber()before doing math.
Get Sunrise and Sunset Times for a Whole Year
Pass date_start and date_end (both YYYY-MM-DD) to get up to 365 days in one request. When you do, results is an array of daily objects instead of a single object. Code written for one date will break on a range, so keep that in mind.
Here’s how to find the earliest and latest sunsets of the year:
const days = await getSunTimes(38.6245, -90.1858, {
date_start: '2026-01-01',
date_end: '2026-12-31',
time_format: 24,
});
console.log(days.length); // one object per day
// 24-hour "HH:MM:SS" strings sort correctly as plain text
const bySunset = [...days].sort((a, b) => a.sunset.localeCompare(b.sunset));
const earliest = bySunset[0];
const latest = bySunset.at(-1);
console.log(`Earliest sunset: ${earliest.sunset} on ${earliest.date}`);
console.log(`Latest sunset: ${latest.sunset} on ${latest.date}`);
365
Earliest sunset: 16:41:30 on 2026-12-06
Latest sunset: 20:31:42 on 2026-06-28
Fun fact hiding in that output: the earliest sunset isn’t on the shortest day of the year (December 21). It’s about two weeks before.
A range longer than a year returns INVALID_DATE. For a single day, use date=2026-12-21, or the words today or tomorrow.
Check if the Sun Has Set Yet
A common use is a countdown, or a simple “is it dark yet” check. With formatted=0 you can compare the times to new Date() directly:
const sun = await getSunTimes(38.6245, -90.1858, { formatted: 0 });
const now = new Date();
const sunset = new Date(sun.sunset);
const dusk = new Date(sun.dusk);
if (sun.sun_status !== 'normal') {
console.log(`No sunset today (${sun.sun_status})`);
} else if (now < sunset) {
const mins = Math.round((sunset - now) / 60000);
console.log(`Sunset in ${Math.floor(mins / 60)}h ${mins % 60}m`);
} else if (now < dusk) {
console.log('The sun is down, but it is still light out');
} else {
console.log("It's dark");
}
Sunset in 4h 37m
Compare Date objects, not the strings. A sunset after local midnight (it happens in the far north in summer) carries the next calendar date.
Handle the Arctic and Antarctic
Near the poles, the sun sometimes doesn’t rise or set at all. When that happens, sunrise, sunset and day_length come back as null, and sun_status tells you why:
const sun = await getSunTimes(69.6492, 18.9553, { date: '2026-12-21' }); // Tromsø, Norway
console.log(sun.sun_status, sun.sunrise, sun.sunset, sun.dawn, sun.dusk);
polar_night null null 9:28:22 AM 1:56:04 PM
sun_status is normal, midnight_sun (the sun never sets) or polar_night (it never rises). Notice there’s still civil twilight in Tromsø that day, so dawn and dusk have values. The moon works the same way: moonrise or moonset can be null, with moon_always_up or moon_always_down set to true.
If your app could ever be used up north, check for null before you format a time.
Cache Results in Node
Sunrise and sunset for a place only change once a day, and times for a past date never change. If you’re calling the API from a server, cache them:
const cache = new Map();
async function getSunTimesCached(lat, lng, date) {
const key = `${lat},${lng},${date}`;
if (!cache.has(key)) {
cache.set(key, getSunTimes(lat, lng, { date }).catch((err) => {
cache.delete(key); // don't cache failures
throw err;
}));
}
return cache.get(key);
}
Caching the promise (not the result) means two requests for the same key at the same time only hit the API once. In my test, the first call took 232 ms and the second took under a millisecond.
For something long-running, swap the Map for Redis or whatever cache you already have.
Everything in the Response
You get a lot more than sunrise and sunset. Here’s a real response for St. Louis on November 21, 2026:
{
"results": {
"date": "2026-11-21",
"sunrise": "6:47:15 AM",
"sunset": "4:45:45 PM",
"first_light": "5:14:34 AM",
"last_light": "6:18:25 PM",
"dawn": "6:18:33 AM",
"dusk": "5:14:27 PM",
"solar_noon": "11:46:40 AM",
"golden_hour": "4:06:05 PM",
"day_length": "9:58:30",
"nautical_twilight_begin": "5:46:11 AM",
"nautical_twilight_end": "5:46:48 PM",
"timezone": "America/Chicago",
"utc_offset": -360,
"sun_altitude": 31.38,
"sun_azimuth": 180,
"sunrise_azimuth": 114.86,
"sunset_azimuth": 245.02,
"moonrise": "2:32:10 PM",
"moonset": "3:20:41 AM",
"moon_illumination": 88.83,
"moon_phase": "Waxing Gibbous",
"moon_phase_value": 0.39,
"moon_always_up": false,
"moon_always_down": false,
"elevation": 126,
"sun_status": "normal",
"golden_hour_morning": { "begin": "6:29:33 AM", "end": "7:26:55 AM" },
"golden_hour_evening": { "begin": "4:06:05 PM", "end": "5:03:27 PM" },
"blue_hour_morning": { "begin": "6:18:33 AM", "end": "6:29:33 AM" },
"blue_hour_evening": { "begin": "5:03:27 PM", "end": "5:14:27 PM" }
},
"status": "OK",
"tzid": "America/Chicago"
}
The Twilight Fields
There are three kinds of twilight and the names don’t make the order obvious, so here they are from darkest to brightest:
first_lightandlast_lightare astronomical twilight, with the sun 18 degrees below the horizon. It’s the faintest brightening of the sky, and the one astrophotographers care about.nautical_twilight_beginandnautical_twilight_endput the sun 12 degrees below the horizon.dawnandduskare civil twilight, 6 degrees below. There’s enough light to be outside without a flashlight. This is the one most apps want when they ask “is it dark yet.”
Golden Hour and Blue Hour
golden_hour_morning and golden_hour_evening are { begin, end } windows with the sun between 4 degrees below and 6 degrees above the horizon. blue_hour_morning and blue_hour_evening cover the deeper light just outside that, between 4 and 6 degrees below. They meet exactly, so blue_hour_morning.end equals golden_hour_morning.begin.
The single golden_hour field is the start of the evening golden hour. It’s kept for older code, so use the window fields in anything new.
A Few Gotchas
utc_offsetis in minutes, not hours.-360means UTC-6.day_lengthis anH:MM:SSstring by default, and a number of seconds withformatted=0.- Azimuths are compass bearings, with north at 0 and running clockwise. A
sunset_azimuthof245means the sun sets in the southwest. sun_altitudeandsun_azimuthare measured at solar noon.sunrise_azimuthandsunset_azimuthare measured at those events.
Other Parameters
elevation: sunrise and sunset are adjusted for terrain elevation automatically (from ETOPO1 data). Higher up means an earlier sunrise and a later sunset. Passelevation=falseto compute at sea level, or a number in meters to override it. The elevation used comes back in the response.callback: for JSONP, passcallback=yourFunctionNameand the response comes back as JavaScript wrapped in that function. With CORS enabled, you shouldn’t need this unless you’re stuck in an old environment.
If you’re using an AI coding assistant, the API page has a plain-text reference you can paste in before asking for code, plus an OpenAPI spec for Postman or generating a typed client.
API or SunCalc?
The other common way to do this in JavaScript is SunCalc, a small library that calculates sun and moon positions on the client. It’s a good library, and it works offline.
Here’s when I’d use the API instead:
- You want times already formatted in the location’s timezone without figuring out the timezone yourself.
- You want terrain elevation factored in.
- You want golden hour, blue hour, moon phase and a full year of dates without writing that logic.
If you need it to work with no network connection, use SunCalc.
SunriseSunset.io vs. Sunrise-Sunset.org
The names are almost the same, so people mix them up. Sunrise-Sunset.org is a separate API, and it’s a good one. Full disclosure: I run SunriseSunset.io. Here’s how they compare as of November 2026 (Sunrise-Sunset.org’s v2):
- Both: free, no key, CORS enabled, times in the location’s own timezone, ISO 8601 times, golden hour and blue hour, and a required visible link back.
- Date ranges: up to 365 days per request here, 366 there.
- Elevation: SunriseSunset.io factors in terrain elevation. Sunrise-Sunset.org uses the standard sea-level horizon and has no elevation setting.
- Rate limits: none enforced here. Sunrise-Sunset.org answers 429 with a
Retry-Afterheader if you send too much too fast. - Extras on their side: sun azimuth at sunrise and sunset, plain HTTP for devices that can’t do TLS, and an MCP server for AI agents.
If you’re on their older v1 endpoint (/json), know that it returns UTC by default. Pick either one; just cache the results and keep the link back.
Attribution and Usage
The API is free for personal and commercial use. The only requirement is a visible link back to SunriseSunset.io wherever you show the data:
Powered by <a href="https://sunrisesunset.io">SunriseSunset.io</a>
There are no enforced rate limits, but please cache. The API runs on Cloudflare’s edge with P99 response times under 50 ms, and there’s a status page if you want to keep an eye on it.
What People Build With It
A few things I’ve seen it used for:
- Photography apps showing golden hour and blue hour for a spot.
- Astrophotography planning with
last_lightandmoon_illuminationto find dark windows. - Hiking apps that warn you when your return time is after
last_light. - Smart home automations that turn lights on at civil dusk.
- Religious observance apps that work out prayer or Sabbath times from the sunset and twilight fields.
- Wedding planners pairing
golden_hour_eveningwithsunset_azimuthto time the ceremony and face the sunset.
If you build something with it, I’d love to see it. Grab the docs at sunrisesunset.io/api and make your first request. No signup needed.
Slap a sticker on this post
Comments
Loading comments…