Code Monkey home page Code Monkey logo

remix-auth-spotify's Introduction

Remix Auth - Spotify Strategy

The Spotify strategy is used to authenticate users against a Spotify account. It extends the OAuth2Strategy.

The strategy supports refreshing expired access tokens. The logic for this is stolen from heavily inspired by remix-auth-supabase – thanks @mitchelvanbever!

Supported runtimes

Runtime Has Support
Node.js
Cloudflare

How to use

Create application in Spotify developer dashboard

  1. Go to the Spotify developer dashboard and sign in with your account
  2. Click Create an app and give the application a suitable name and description
  3. Click Edit settings and add
    • http://localhost:3000 under Website
    • http://localhost:3000/auth/spotify/callback under Redirect URIs (remember to hit Add)
  4. Hit Save at the bottom of the modal
  5. Grab your client ID and secret from the dashboard overview, and save them as env variables

Remember to update Website and Redirect URIs if/when deploying your app.

Install remix-auth and the Spotify strategy

npm install remix-auth remix-auth-spotify
# or
yarn add remix-auth remix-auth-spotify

Setup env variables, sessionStorage, strategy and authenticator

# .env
SPOTIFY_CLIENT_ID="your client id"
SPOTIFY_CLIENT_SECRET="your client secret"
SPOTIFY_CALLBACK_URL="your callback url" # e.g. http://localhost:3000/auth/spotify/callback
// app/services/session.server.ts
import { createCookieSessionStorage } from '@remix-run/node';

export const sessionStorage = createCookieSessionStorage({
    cookie: {
        name: '_session', // use any name you want here
        sameSite: 'lax',
        path: '/',
        httpOnly: true,
        secrets: ['s3cr3t'], // replace this with an actual secret from env variable
        secure: process.env.NODE_ENV === 'production', // enable this in prod only
    },
});

export const { getSession, commitSession, destroySession } = sessionStorage;
// app/services/auth.server.ts
import { Authenticator } from 'remix-auth';
import { SpotifyStrategy } from 'remix-auth-spotify';

import { sessionStorage } from '~/services/session.server';

if (!process.env.SPOTIFY_CLIENT_ID) {
    throw new Error('Missing SPOTIFY_CLIENT_ID env');
}

if (!process.env.SPOTIFY_CLIENT_SECRET) {
    throw new Error('Missing SPOTIFY_CLIENT_SECRET env');
}

if (!process.env.SPOTIFY_CALLBACK_URL) {
    throw new Error('Missing SPOTIFY_CALLBACK_URL env');
}

// See https://developer.spotify.com/documentation/general/guides/authorization/scopes
const scopes = ['user-read-email'].join(' ');

export const spotifyStrategy = new SpotifyStrategy(
    {
        clientID: process.env.SPOTIFY_CLIENT_ID,
        clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
        callbackURL: process.env.SPOTIFY_CALLBACK_URL,
        sessionStorage,
        scope: scopes,
    },
    async ({ accessToken, refreshToken, extraParams, profile }) => ({
        accessToken,
        refreshToken,
        expiresAt: Date.now() + extraParams.expiresIn * 1000,
        tokenType: extraParams.tokenType,
        user: {
            id: profile.id,
            email: profile.emails[0].value,
            name: profile.displayName,
            image: profile.__json.images?.[0]?.url,
        },
    }),
);

export const authenticator = new Authenticator(sessionStorage, {
    sessionKey: spotifyStrategy.sessionKey,
    sessionErrorKey: spotifyStrategy.sessionErrorKey,
});

authenticator.use(spotifyStrategy);

Setup authentication routes

// app/routes/auth.spotify.tsx
import type { ActionFunctionArgs } from '@remix-run/node';
import { redirect } from '@remix-run/node';

import { authenticator } from '~/services/auth.server';

export function loader() {
    return redirect('/login');
}

export async function action({ request }: ActionFunctionArgs) {
    return await authenticator.authenticate('spotify', request);
}
// app/routes/auth.spotify.callback.tsx
import type { LoaderFunctionArgs } from '@remix-run/node';

import { authenticator } from '~/services/auth.server';

export function loader({ request }: LoaderFunctionArgs) {
    return authenticator.authenticate('spotify', request, {
        successRedirect: '/',
        failureRedirect: '/login',
    });
}
// app/routes/logout.tsx
import type { ActionFunctionArgs } from '@remix-run/node';
import { json, redirect } from '@remix-run/node';

import { destroySession, getSession } from '~/services/session.server';

export async function action({ request }: ActionFunctionArgs) {
    return redirect('/', {
        headers: {
            'Set-Cookie': await destroySession(
                await getSession(request.headers.get('cookie')),
            ),
        },
    });
}

export function loader() {
    throw json({}, { status: 404 });
}

Use the strategy

spotifyStrategy.getSession() works similar to authenticator.isAuthenticated(), only it handles refreshing tokens. If you don't need to refresh tokens in your app, feel free to use authenticator.isAuthenticated() instead.

// app/routes/_index.tsx
import type { LoaderFunctionArgs } from '@remix-run/node';
import { Form, useLoaderData } from '@remix-run/react';

import { spotifyStrategy } from '~/services/auth.server';

export async function loader({ request }: LoaderFunctionArgs) {
    return spotifyStrategy.getSession(request);
}

export default function Index() {
    const data = useLoaderData<typeof loader>();
    const user = data?.user;

    return (
        <div style={{ textAlign: 'center', padding: 20 }}>
            <h2>Welcome to Remix!</h2>
            <p>
                <a href="https://docs.remix.run">Check out the docs</a> to get
                started.
            </p>
            {user ? (
                <p>You are logged in as: {user?.email}</p>
            ) : (
                <p>You are not logged in yet!</p>
            )}
            <Form action={user ? '/logout' : '/auth/spotify'} method="post">
                <button>{user ? 'Logout' : 'Log in with Spotify'}</button>
            </Form>
        </div>
    );
}

remix-auth-spotify's People

Contributors

github-actions[bot] avatar josteinkringlen avatar renovate-bot avatar renovate[bot] avatar semantic-release-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

eligundry

remix-auth-spotify's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency eslint to v8.57.0
  • chore(deps): update dependency typescript to v5.4.5
  • chore(deps): update dependency eslint to v9
  • chore(deps): update dependency eslint-plugin-simple-import-sort to v12
  • chore(deps): update dependency eslint-plugin-unicorn to v52
  • chore(deps): update typescript-eslint monorepo to v7 (major) (@typescript-eslint/eslint-plugin, @typescript-eslint/parser)
  • 🔐 Create all rate-limited PRs at once 🔐

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/bump.yml
  • actions/checkout v4
  • actions/setup-node v4
  • bahmutov/npm-install v1
.github/workflows/main.yml
  • actions/checkout v4
  • actions/setup-node v4
  • bahmutov/npm-install v1
  • actions/checkout v4
  • actions/setup-node v4
  • bahmutov/npm-install v1
  • actions/checkout v4
  • actions/setup-node v4
  • bahmutov/npm-install v1
  • actions/checkout v4
  • actions/setup-node v4
  • bahmutov/npm-install v1
  • actions/checkout v4
  • actions/setup-node v4
  • bahmutov/npm-install v1
  • actions/checkout v4
  • actions/setup-node v4
  • bahmutov/npm-install v1
.github/workflows/publish.yml
  • actions/checkout v4
  • actions/setup-node v4
.github/workflows/release.yml
  • actions/checkout v4
  • actions/setup-node v4
  • changesets/action v1
.github/workflows/renovate-changesets.yml
  • mscharley/dependency-changesets-action v1.0.6
npm
package.json
  • remix-auth-oauth2 ^1.6.0
  • @arethetypeswrong/cli 0.13.5
  • @babel/core 7.23.6
  • @babel/preset-env 7.23.6
  • @babel/preset-react 7.23.3
  • @babel/preset-typescript 7.23.3
  • @changesets/cli 2.27.1
  • @remix-run/node 2.4.1
  • @remix-run/react 2.4.1
  • @remix-run/server-runtime 2.4.1
  • @typescript-eslint/eslint-plugin 6.16.0
  • @typescript-eslint/parser 6.16.0
  • c8 8.0.1
  • cz-conventional-changelog 3.3.0
  • eslint 8.56.0
  • eslint-config-prettier 9.1.0
  • eslint-plugin-prettier 5.1.2
  • eslint-plugin-simple-import-sort 10.0.0
  • eslint-plugin-unicorn 50.0.1
  • prettier 3.1.1
  • publint 0.2.7
  • react 18.2.0
  • remix-auth 3.6.0
  • ts-node 10.9.2
  • tsup 8.0.1
  • typescript 5.3.3
  • vitest 1.1.0
  • @remix-run/server-runtime >=1.1.0
  • remix-auth >=3.2.2

  • Check this box to trigger a request for Renovate to run again on this repository

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.