B-Side Breaks is a marketing product that connects Spotify listening behavior with live-event discovery and travel intent. The app behaves like a fusion of Spotify, Skyscanner, and Ticketmaster:
- Spotify provides the user taste signal.
- Ticketmaster provides real live events that match the inferred music scene.
- Skyscanner receives high-intent travel traffic through generated flight-search links.
- MongoDB stores behavioral analytics, recommendation history, artist exposure, and AI-generated marketing insights.
The product is designed as a consumer-facing recommendation experience plus an internal analytics dashboard for partner marketing teams.
The user logs in with Spotify. The app reads their top artists, tracks, genres, and profile metadata. An AI agent turns that musical DNA into music scenes and event-search instructions. Ticketmaster is queried for live events in relevant markets. The app returns up to three travel/event recommendations and links the user to:
- the live event on Ticketmaster
- a flight search on Skyscanner
- sharing actions that amplify the trip recommendation
Behind the scenes, the app tracks behavior such as page views, clicks, screen time, generated recommendations, shown artists, and AI insights. This creates a marketing intelligence layer for the three partners.
Spotify benefits because listening history becomes an actionable discovery signal. The app demonstrates how Spotify taste data can power lifestyle and travel recommendations.
Main marketing signals:
- top artists
- top genres
- taste profile
- inferred music scenes
- user engagement after music-based personalization
Ticketmaster benefits because the app sends motivated users to specific live events. The recommendations are not generic: they are matched to the user's music profile and presented as part of a destination plan.
Main marketing signals:
- event click intent
- recommended event impressions
- artist impressions
- category performance
- city/event combinations
Skyscanner benefits because each recommendation turns a concert into a possible city break. The product generates flight-search links for the destination city, creating qualified travel intent.
Main marketing signals:
- destination interest
- flight-search clicks
- city demand by music segment
- comparison between event intent and travel intent
- Next.js App Router
- React 19
- NextAuth with Spotify OAuth
- Spotify Web API
- Ticketmaster Discovery API
- Google GenAI / Gemini-compatible model
- MongoDB Atlas or local MongoDB
- Tailwind CSS and shadcn-style UI primitives
- lucide-react icons
| Route | Type | Purpose |
|---|---|---|
/ |
Page | Landing/login screen with Spotify authentication. |
/generate |
Page | Main recommendation experience. Fetches Spotify DNA, calls recommendation API, displays trips. |
/analisis |
Page | Internal marketing dashboard. Not linked from navigation. Accessed directly by URL. |
/canvas |
Page | Legacy/local visual card view for stored recommendations. |
/api/auth/[...nextauth] |
API | NextAuth Spotify OAuth handler. |
/api/spotify/top |
API | Returns user's musical DNA from Spotify. |
/api/recommendations |
API | AI + Ticketmaster recommendation engine. |
/api/analytics/track |
API | Stores behavior events in MongoDB. |
/api/analytics/summary |
API | Returns dashboard data and generates AI insights. |
- User opens
/. - User logs in with Spotify through NextAuth.
- After authentication, the app redirects to
/generate. /generatecalls/api/spotify/top./api/spotify/topreads:- Spotify profile
- top artists
- top tracks
- top genres
/generatesends the musical DNA to/api/recommendations./api/recommendationsasks the AI agent to infer:- core genres
- adjacent genres
- music scenes
- target countries/cities
- Ticketmaster keywords
- The API queries Ticketmaster events for those scenes.
- Events are scored against the Spotify profile and AI taste profile.
- The app returns up to three trip recommendations:
- destination
- event
- venue
- date
- artist
- Ticketmaster URL
- Skyscanner flight URL
- reasoning
- The frontend displays the cards in a carousel.
- Behavior is tracked automatically:
- page views
- clicks
- screen time
- Recommendation snapshots are stored:
- musical DNA
- taste profile
- recommendations
- shown artists
/analisisreads MongoDB aggregations and displays:- users
- sessions
- clicks
- page views
- total product time
- top pages
- highest-intent clicks
- partner intent split
- recommended destinations
- most recommended artists
- recent recommendation log
- The dashboard can generate an AI marketing insight using
POST /api/analytics/summary.
Important: /analisis is excluded from analytics tracking so dashboard usage does not contaminate product behavior metrics.
SPOTIFY_CLIENT_ID="..."
SPOTIFY_CLIENT_SECRET="..."
NEXTAUTH_SECRET="..."
NEXTAUTH_URL="http://localhost:3000"
TICKETMASTER_API_KEY="..."
GEMINI_API_KEY="..."
GEMINI_MODEL="gemma-4-31b-it"
MONGODB_URI="mongodb+srv://USER:[email protected]/bsidebreaks?retryWrites=true&w=majority"
MONGODB_DB="bsidebreaks"npm install
npm run dev
npm run build
npm run lint
npm run mongo:indexesFile: app/lib/auth.js
authOptions
Configures NextAuth with Spotify. It requests scopes for email/private profile, top listening data, and playlist modification.
Main responsibility:
- set Spotify OAuth provider
- attach
accessTokento session - refresh expired Spotify tokens
- expose session errors through
session.error
refreshAccessToken(token)
Refreshes Spotify access tokens using the stored refresh token.
Flow:
- Sends a
POSTrequest tohttps://accounts.spotify.com/api/token. - Uses Basic auth with Spotify client id/secret.
- Returns a new token object with:
accessTokenaccessTokenExpiresrefreshToken
- If refresh fails, marks the token with
RefreshAccessTokenError.
File: app/lib/spotify.js
getTopArtists(accessToken)
Calls Spotify /me/top/artists and returns the user's top artists.
Key params:
limit: 10time_range: medium_term
getTopTracks(accessToken)
Calls Spotify /me/top/tracks and returns the user's top tracks.
getUserProfile(accessToken)
Calls Spotify /me and returns the user profile.
getMusicalDNA(accessToken)
Builds the normalized Spotify profile used by the recommendation system.
Output fields:
usertopGenrestopArtiststopTracksmood
This function combines profile, artists, and tracks in parallel, then extracts a compact taste profile for the AI agent.
File: app/lib/spotify.js
searchTicketmasterEventsForScenes(scenes)
Searches Ticketmaster events based on AI-generated scenes.
Main steps:
- Reads
TICKETMASTER_API_KEY. - Converts music scenes into keyword/country searches.
- Calls Ticketmaster Discovery API.
- Normalizes events.
- Deduplicates by event id.
buildTicketmasterSceneSearches(scenes)
Turns scenes into individual searches. For example, one scene can become several searches by combining:
- Ticketmaster keywords
- country codes
- fallback null country search
normalizeTicketmasterEvent(event, search)
Converts raw Ticketmaster events into the app's internal event shape.
Normalized fields:
idnameurlimagedatetimescenematchedKeywordartistsvenue
getTicketmasterAttractionsForArtists(artists)
Legacy/helper function that searches Ticketmaster attractions directly from artist names and optionally fetches events for the matched attraction.
File: app/api/spotify/top/route.js
GET()
Server endpoint that returns musicalDNA.
Flow:
- Reads server session.
- Rejects if unauthenticated or Spotify token refresh failed.
- Calls
getMusicalDNA(session.accessToken). - Returns
{ musicalDNA }.
File: app/api/recommendations/route.js
POST(req)
Main recommendation endpoint.
Input:
musicalDNAexcludedEventIds
Flow:
- Validates session.
- Validates musical DNA.
- Builds or retrieves AI taste profile.
- Searches Ticketmaster events.
- Applies fallback searches if not enough events exist.
- Filters already-seen events when possible.
- Scores events and builds recommendations.
- Stores recommendation analytics asynchronously.
- Returns recommendation cards.
generateTasteProfile(musicalDNA, options)
Builds a taste profile using the AI agent. Falls back to local heuristics when:
- AI is skipped
- Gemini key is missing
- AI times out
- AI returns an invalid response
buildTasteProfilePrompt(dna)
Creates the prompt used by the AI agent. It asks for compact JSON containing:
coreGenresadjacentGenresmusicScenesfallbackMusicScenes
generateJson(prompt, maxOutputTokens)
Calls Google GenAI and expects JSON output. Includes retry behavior for transient AI errors.
normalizeTasteProfile(profile)
Normalizes different possible AI response key names into a stable internal format.
buildLocalTasteProfile(dna)
Creates a non-AI fallback profile from Spotify artists and genres.
buildFallbackTasteProfile(dna, tasteProfile)
Creates broader backup scenes when the primary AI profile does not produce enough valid events.
buildLocalFallbackScenes(keywords, markets)
Builds simple backup Ticketmaster search scenes from known keywords and markets.
getRelatedDiscoveryKeywords(genreText)
Maps genre/artist text into related discovery keywords. Examples:
- Punjabi/Bollywood terms ->
punjabi,bhangra,bollywood,desi - Latin terms ->
latin,reggaeton,urbano - Electronic terms ->
electronic,techno,house - Hip-hop terms ->
hip hop,rap,r&b,soul - Rock terms ->
indie,alternative,rock,punk
buildMainRecommendations(dna, tasteProfile, events)
Creates the final recommendation objects shown to the user.
Each recommendation includes:
categoryevent_idcitycountryevent_nameevent_urlevent_datevenuediscovery_artistspotify_playlist_vibereasoningflightURLimage
selectBestProfileMatches(dna, tasteProfile, events)
Filters and sorts events by score.
scoreEventForProfile(event, dna, tasteProfile)
Scores each Ticketmaster event using:
- top artist text matches
- top genre matches
- AI core genre matches
- AI scene keyword matches
- event metadata availability
buildFlightURL(originIata, destinationIata)
Builds a Skyscanner URL from origin and destination IATA codes.
getIataForCity(city)
Maps selected city names to IATA codes used for Skyscanner search links.
File: app/generate/page.tsx
GeneratePage()
Main authenticated experience.
Responsibilities:
- guard unauthenticated users
- fetch Spotify DNA
- request recommendations
- show loading progress
- store seen event ids in
sessionStorage - display trip cards
- allow retry/regeneration
generateTrips()
Client-side orchestration function.
Flow:
- Calls
/api/spotify/top. - Calls
/api/recommendations. - Preloads hero images.
- Stores seen event ids.
- Updates recommendation state.
TripGenerationStepBars()
Shows staged progress:
- Taste Discovery
- Genre Matching
- Finding Events
- Tailoring matches
TripCard()
Displays each recommendation card with:
- image
- category
- destination
- event name
- reasoning
- date
- venue
- artist
- Ticketmaster button
- Skyscanner button
- share action
TripDetailsDialog()
Modal for expanded trip details.
ShareSheet()
Bottom sheet for sharing through:
- native share
- copy link
- X
File: components/analytics/AnalyticsTracker.tsx
AnalyticsTracker()
Global client-side tracker mounted in the root layout.
Tracks:
page_viewclickscreen_time
Important behavior:
- stores anonymous id in
localStorage - stores session id in
localStorage - uses
sendBeaconfor screen time - uses
fetch(..., keepalive: true)for normal events - ignores
/analisisso dashboard activity does not contaminate product metrics
getStoredId(key, prefix)
Returns an existing browser id or creates a new UUID-based id.
getClickTarget(target)
Finds nearest clickable element:
abutton[role='button']
File: lib/mongodb.js
getMongoClient()
Creates and reuses a MongoDB client connection. If the connection promise fails, it resets the promise so later requests can retry.
getDb()
Returns the configured database.
isMongoConfigured()
Checks whether MONGODB_URI exists.
File: lib/analytics.js
ensureAnalyticsIndexes()
Creates indexes for analytics collections.
Collections:
analytics_eventsuser_sessionsusersai_insightsrecommendation_snapshotsrecommendation_artist_stats
buildUserIdentity(session, anonymousId)
Builds the user identity used in analytics.
If Spotify email exists:
spotify:[email protected]Otherwise:
anonymous:<anonymousId>trackAnalyticsEvent({ session, anonymousId, event, request })
Stores raw and summarized behavior data.
Writes to:
analytics_eventsuser_sessionsusers
Uses:
insertOnefor raw eventsupdateOnewith$inc,$set,$setOnInsert,$addToSetfor session/user summaries
recordRecommendationSnapshot({ session, musicalDNA, tasteProfile, recommendations })
Stores the result of every recommendation generation.
Writes to:
recommendation_snapshotsrecommendation_artist_statsusers
This is the marketing layer that captures which artists, cities, events, and categories were shown to users.
buildRecommendationArtistStatUpdates(identity, recommendations, now)
Builds MongoDB upsert operations that aggregate shown artists per user.
Tracked fields:
artistimpressionseventIdscitiescountriescategoriesrecentEventslastEventfirstShownAtlastShownAt
getAnalyticsOverview()
Builds dashboard data from MongoDB.
It aggregates:
- total events
- users
- sessions
- clicks
- page views
- screen time
- top pages
- event type mix
- top clicks
- latest product sessions
- recommended destinations
- most recommended artists
- recent recommendation log
- latest AI insight
It excludes /analisis from product metrics.
generateAnalyticsInsight()
Calls the AI agent to summarize marketing behavior.
Returns JSON with:
summaryopportunitiesriskspartnerNotes.spotifypartnerNotes.skyscannerpartnerNotes.ticketmaster
Stores the result in ai_insights.
describeMongoError(error)
Converts MongoDB/network/SSL errors into user-friendly dashboard messages.
isMongoConnectionError(error)
Detects connection errors so tracking can degrade gracefully with HTTP 202 instead of breaking product usage.
File: app/api/analytics/track/route.js
POST(req)
Accepts tracking events from the browser.
Returns:
200when stored202when MongoDB has a connection issue400when payload is invalid
File: app/api/analytics/summary/route.js
GET()
Returns dashboard overview data.
POST()
Generates and stores a fresh AI insight.
File: app/analisis/page.tsx
AnalisisPage()
Internal dashboard for partner marketing teams.
Sections:
- headline metrics
- AI agent insight
- partner notes
- highest-intent clicks
- partner intent split
- top pages
- recommended destinations
- most recommended artists
- latest product sessions
- recent recommendation log
GenerateInsightButton()
Client component that calls POST /api/analytics/summary and refreshes the dashboard.
BarRow()
Horizontal CSS bar visualization for click/page metrics.
VerticalBars()
Vertical CSS bar visualization for event type mix.
ResponsiveTable()
Scrollable table wrapper for smaller screens.
Append-only event stream.
Stores:
- page views
- clicks
- screen time
- page
- session id
- user key
- viewport
- user agent
- referrer
- created timestamp
Incremental session summary.
Stores:
- session id
- user key
- started time
- last seen time
- pages
- event count
- click count
- page view count
- total duration
User-level behavior summary.
Stores:
- Spotify/anonymous user key
- profile fields
- first seen
- last seen
- total events
- total duration
- recommendation runs
Stores each recommendation run.
Stores:
- user key
- musical DNA
- taste profile
- recommendations
- created timestamp
Aggregated artist exposure.
Stores:
- user key
- artist
- impressions
- event ids
- cities
- countries
- categories
- recent events
- last event
AI-generated marketing summaries.
Stores:
- summary
- opportunities
- risks
- partner notes
- created timestamp
The app can support these KPI views:
- Spotify-to-trip conversion
- top recommended artists
- destination demand by music taste
- Ticketmaster event click-through
- Skyscanner flight-search click-through
- partner intent split
- top product pages
- session duration
- recommendation freshness
- AI-generated strategic opportunities
- The dashboard route is intentionally not linked from the public UI.
- Analytics tracking is designed to degrade gracefully if MongoDB is temporarily unavailable.
- Recommendation generation still works even if analytics storage fails.
- AI generation has local fallbacks where possible.
- The product is mobile-first for the consumer trip flow and desktop-friendly for the internal analytics dashboard.



