Introducing a new way to review your PRs.

Read the announcement

nusmodifications / nusmods

🏫 Official course planning platform for National University of Singapore.

View on GitHub

20 documents · Updated Nov 6, 2026

docs / serverless-and-external-apis

Serverless and external APIs

The website uses public data services and serverless handlers to support timetable planning, student-linked NUS actions, campus tools, and file export. The main trust boundary is the NUS API layer: public timetable data can be read without a user session, while sign-in and Course Planning Exercise data pass through protected website endpoints.

Service boundaries

Each service has a narrow product role. The browser uses public sources for read-only planning data and sends user-linked actions through the website's serverless API.

Service areaProduct roleAccess boundary
NUS dataSupplies module, venue, faculty, and Course Planning Exercise data.Public data API
OptimisationFinds a useful timetable from selected modules and preferences.Public POST endpoint
NUS authenticationStarts single sign-on and identifies the signed-in student.Protected serverless boundary
Course Planning ExerciseReads and saves a student's planning choices.NUS authentication required
Transport and weatherAdds live campus context.External services
GitHub-backed dataSupplies contributor and venue-location data.Cached proxy with local fallback
ExportRenders timetable state as PNG or PDF.Public export endpoint with input checks

Website API paths run as Vercel handlers or route to the public NUS data API. The export service runs as a separate public service. References: website/vercel.json• L4-8, website/vercel.json• L21-46, website/…/nusmods.js• L3-20

NUS data services

The NUS data service is the main source for timetable and academic data. It groups resources by academic year so the website can show current data and selected archived terms.

The website uses this data in three related ways:

  • The module view loads a module list and then obtains details for selected modules.
  • The venue view loads term venue data for campus planning.
  • The Course Planning Exercise loads its own module list for student choices.

When a special term needs data from another academic year, the website can read the matching archived resource. This keeps term-specific views useful without changing the browser's saved timetable. References: website/…/nusmods.js• L23-85, website/…/moduleBank.ts• L23-27, website/…/moduleBank.ts• L89-149, website/…/venueBank.ts• L7-14, website/…/mpe.ts• L58-60

Timetable optimisation

The optimisation service turns selected modules and planning preferences into a suggested timetable. It does not replace the browser's timetable state; it returns a planning result and links that the user can inspect or share.

Optimisation request

The request separates hard limits from soft preferences. Hard limits remove timetable choices that cannot be used. Soft preferences rank the remaining schedules.

  • Free days and the allowed class-time range.
  • Recorded lesson types.
  • Pinned classes that must remain fixed.
  • Lunch and maximum consecutive-lesson preferences.
  • Academic year, semester, and module codes.

Pinned classes must belong to the requested modules and identify a valid lesson type and class number. Physical pins must also meet the selected day and time limits. Recorded pins do not require physical attendance. References: website/…/models.go• L18-97, website/…/modules.go• L121-205, website/…/api_test.go• L338-513

The service gets lesson choices from NUS data, removes choices that break hard limits, and searches the remaining combinations. It keeps Sunday as the seventh timetable day and avoids clashes when lesson weeks overlap.

The search gives fixed lessons priority. It then favors lessons with fewer choices and ranks schedules by user comfort and travel distance. These are preferences, so a result can be the best available schedule without meeting every soft goal. Venue coordinates support the travel part of this ranking; the bundled venue map provides the optimiser's room and location data for known venues. References: website/…/solver.go• L31-81, website/…/solver.go• L104-219, website/…/solver.go• L272-336, website/…/modules.go• L209-240, website/…/venues.json• L1-20

Schedule result

The response contains selected assignments, seven day lists, travel scores, an overall score, and two NUSMods links. One link contains only assignments that fit the search limits. The other fills missing lesson types with fallback classes so the user can open a complete timetable view.

The browser shows both links and marks lesson types that it could not place. This makes an incomplete result useful for planning without presenting it as a fully valid timetable. References: website/…/models.go• L108-141, website/…/optimiser.ts• L19-47, website/…/OptimiserContent.tsx• L135-177, website/…/solver_test.go• L10-61

NUS authentication boundary

The NUS authentication boundary protects actions that act for a student. It uses NUS single sign-on through SAML and gives the browser a short-lived token after the callback is checked.

The sign-in flow follows this sequence:

sequenceDiagram
    participant Browser
    participant API as Website API
    participant NUS as NUS SSO
    participant Store as Browser token store

    Browser->>API: Request sign-in link with callback
    API->>API: Check callback domain
    API-->>Browser: Return sign-in link
    Browser->>NUS: Sign in
    NUS->>API: Return SAML response
    API->>API: Validate response and callback
    API-->>Browser: Redirect with token
    Browser->>Store: Save token
    Browser->>API: Call protected endpoint
    API->>API: Verify token and user identity

Only approved NUSMods domains and local development callbacks are accepted. Protected requests read the token from the authorization header and reject missing, expired, or invalid credentials. The browser removes an expired token and asks the student to sign in again. References: website/…/nus-auth.ts• L20-32, website/…/nus-auth.ts• L56-83, website/…/nus-auth.ts• L85-155, website/…/sso.ts• L15-50, website/…/login.ts• L14-39, website/…/mpe.ts• L18-42

Serverless route behavior

The shared route layer gives website handlers a common HTTP boundary. It selects behavior by method, answers cross-origin preflight requests, rejects unsupported methods, and turns unexpected errors into JSON server errors.

EndpointProduct purposeMethods
/api/nus/auth/ssoCreate a sign-in link for a checked callback.GET
/api/nus/auth/loginProcess the NUS SAML response.POST
/api/nus/auth/userReturn the signed-in NUS user.GET
/api/nus/mpe/submissionsRead or save the signed-in user's Course Planning Exercise data.GET, POST, PUT
/api/optimiser/optimiseFind a timetable that matches the request.POST

Server-side authentication metadata and related data files are included with the functions. This keeps the SAML trust work outside the browser. References: website/…/handler.ts• L19-77, website/…/sso.ts• L48-52, website/…/user.ts• L10-19, website/…/submissions.ts• L16-53, website/…/optimise.go• L37-103, website/vercel.json• L4-8

Course Planning Exercise submissions

The Course Planning Exercise lets a signed-in student submit ranked course choices for NUS planning. It records demand and requirement types; it does not allocate courses or check timetable clashes.

The page joins the current NUS module list with the student's saved submission. This lets old saved choices display current module names and credit data. On save, the protected service checks the student identity and submission shape before it sends the ranked choices to NUS-backed storage. References: website/…/MpeContainer.tsx• L128-179, website/…/MpeFormContainer.tsx• L13-65, website/…/submissions.ts• L16-51, website/…/mpe.ts• L20-55

The feature also follows a server-side flag and the Course Planning Exercise schedule. When the exercise is closed, the endpoint returns 404 so a reachable page cannot accept submissions. An expired login clears the page's signed-in state and starts sign-in again. References: website/…/mpe.ts• L106-116, website/…/MpeContainer.tsx• L59-75

Transport and weather services

Transport and weather add live context to campus planning without becoming part of the timetable data store. Their results are optional, so a failed external request affects its view instead of the core timetable.

The map keeps a local list of bus stops and asks the NextBus service for arrival data when a stop view refreshes. The adapter maps arrivals to minutes or known status values such as Arr and -. The Today view uses Singapore-local dates to combine current conditions, a next-day forecast, and a four-day forecast. References: website/…/nextbus.ts• L5-41, website/…/BusStops.tsx• L85-113, website/…/weather.ts• L76-114, website/…/TodayContainer.tsx• L133-169

GitHub-backed data

GitHub-backed services provide community data that changes outside the main timetable API. The website uses a NUSMods proxy so shared responses reduce direct GitHub request pressure.

Contributor data is limited to human users before it reaches the contributor page. Venue locations load once per session, and the website uses bundled venue data when the proxy is unavailable. A debug preference can force the bundled data. References: website/…/github.ts• L7-10, website/…/github.ts• L18-33, website/…/github.ts• L36-67, website/…/ContributorList.tsx• L37-68, website/…/withVenueLocations.tsx• L41-73

Timetable export services

The export service turns the timetable state in the browser into a PNG or PDF download. It renders a view of the selected state; it does not edit or store a second timetable.

The export flow follows these stages:

  1. The browser selects the timetable, color, hidden-module, theme, and display settings.
  2. It serializes that state into an image or PDF URL.
  3. The export endpoint checks the input before render work starts.
  4. A browser renderer opens a timetable-only page and injects the state.
  5. The service returns the rendered file.

This diagram shows how local timetable state becomes a downloaded file.

flowchart LR
    State[Browser timetable state] --> Query[Export URL data]
    Query --> Validate[Validate input]
    Validate --> Render[Render timetable page]
    Render --> File[PNG or PDF download]

Image exports can include a pixel ratio and viewport size. PDF output follows timetable orientation and includes the rendered background. Bad timetable data produces a 422 response. Browser or render failures produce a server error. References: website/…/export.ts• L9-43, website/…/ExportMenu.tsx• L83-109, export/…/image.ts• L13-45, export/…/pdf.ts• L6-20, export/…/handler.ts• L40-92, export/…/render-serverless.ts• L50-93

The renderer needs module details to draw lesson names and related data. It first uses configured local data and then falls back to the NUS data API. Export reliability therefore depends on both the timetable-only page and module data being available. References: export/…/data.ts• L12-57, export/…/render-serverless.ts• L38-66

Cross-service relationships

These services have different trust levels and data roles. Public sources enrich the interface, the optimiser transforms public timetable inputs, and only the NUS boundary grants access to student-linked data.

BoundaryData directionProduct effect
NUS data APINUS data to browser and server toolsBuilds module, venue, and Course Planning Exercise views.
OptimiserBrowser preferences to schedule resultAdds planning help without changing saved timetable state.
NUS SSO and storageBrowser identity and choices through serverless handlersProtects and stores Course Planning Exercise data.
Live campus servicesExternal response to browserAdds current transport and weather context.
GitHub proxyCommunity data to browserShows contributors and venue locations with cache and fallback behavior.
Export serviceBrowser timetable state to rendered fileProduces portable timetable downloads.

The client state and persistence page explains the browser state that feeds the optimiser and export flows. The web application runtime page places these calls in the wider page lifecycle. The timetable optimisation, module prerequisite explorer, venue and transport tools, and timetable export service pages give focused views of related product flows.

References: website/…/nusmods.js• L23-85 website/…/optimiser.ts• L44-47 website/…/mpe.ts• L24-77 website/…/export.ts• L16-43

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the browser optimiser request and response shapes aligned. The page needs both shareable links when the solver cannot place every lesson.
  • Preserve the hand-off between callback checks, token storage, authorization headers, and token verification.
  • Keep the Course Planning Exercise flag and schedule rules aligned with page state and endpoint 404 behavior.
  • Update export input checks and the timetable-only page together when exported state or theme data changes.
  • Keep academic-year URL rules aligned across module, venue, Course Planning Exercise, optimiser, and export requests.
  • Keep the GitHub venue fallback aligned with both the proxy response and bundled venue data.
  • Keep the optimiser's seven-day result and Sunday index aligned with browser day mapping.
  • Keep venue data used by travel scoring synchronized with the source venue data. The optimiser's bundled copy is generated and must not drift from that source.

Important failure modes

TriggerConsequenceGuard
An untrusted callback reaches SSO endpointsA login token could be sent outside an approved site.Check the callback against the allowed domain set.
A missing or expired NUS token reaches a protected endpointThe request fails and the Course Planning Exercise page asks for sign-in.Verify the token and clear it in the browser after expiry.
The Course Planning Exercise is closed while its page remains reachableA closed exercise could accept submissions.Return 404 before read or write handling.
Optimiser input has invalid modules, times, or pinsThe service returns a client error instead of a schedule.Validate request shape, pin ownership, pin existence, and physical pin limits.
A venue has no usable coordinatesTravel scoring cannot measure that part of the route accurately.Use known bundled coordinates and apply the optimiser's unknown-venue handling.
A Sunday class is mapped outside the seven-day resultThe browser can show it on the wrong day or lose it.Keep day indexes aligned from request processing to JSON output.
Weather or shuttle data fails or has an unexpected valueIts view lacks live data or shows an arrival error.Validate each response and keep failure local to the view.
GitHub venue data cannot be fetchedMap markers can lose remote location data.Use bundled venue data and allow a retry after clearing the cached request.
Export data is malformed or the timetable-only page failsThe user receives a 422 or 500 export error.Validate before browser startup and close the browser after render attempts.

Key files

FileWhy to read it
website/vercel.jsonShows API rewrites, cross-origin headers, and serverless file inclusion.
website/…/handler.tsDefines shared method dispatch and error handling.
website/…/nus-auth.tsDefines the SAML trust boundary and token checks.
website/…/sso.tsStarts the NUS sign-in flow.
website/…/login.tsProcesses the SAML response and callback redirect.
website/…/submissions.tsDefines the protected Course Planning Exercise data boundary.
website/…/nusmods.jsDefines the NUS academic-year data resources.
website/…/optimiser.tsDefines the browser optimiser contract.
website/…/README.mdDescribes optimiser goals and hard and soft constraints.
website/…/optimise.goDefines the optimiser HTTP boundary.
website/…/modules.goConverts NUS lesson data into planning choices and venue coordinates.
website/…/solver.goRanks valid choices into a suggested timetable.
website/…/venues.jsonProvides the optimiser's bundled venue locations for travel scoring.
website/…/weather.tsDefines weather inputs and forecast results.
website/…/nextbus.tsDefines the shuttle arrival adapter.
website/…/github.tsDefines proxy, cache, filtering, and venue fallback behavior.
website/…/export.tsBuilds public image and PDF export URLs.
export/…/handler.tsDefines export validation and response handling.
export/…/render-serverless.tsShows the browser render path for PNG and PDF output.