Skip to content
Migrating from NextAuth.js v4? Read our migration guide.
API reference@auth/solid-start

@auth/solid-start

⚠️

@auth/solid-start is currently experimental. The API will change in the future.

SolidStart Auth is the official SolidStart integration for Auth.js. It provides a simple way to add authentication to your SolidStart app in a few lines of code.

Installation

npm install @auth/core @auth/solid-start

AuthError

Base error class for all Auth.js errors. It’s optimized to be printed in the server logs in a nicely formatted way via the logger.error option.

Extends

Constructors

new AuthError(message, errorOptions)

new AuthError(message?, errorOptions?): AuthError
Parameters
ParameterType
message?string | ErrorOptions
errorOptions?ErrorOptions
Returns

AuthError

Overrides

Error.constructor

Properties

cause?

optional cause: Record<string, unknown> & {
  err: Error;
};
Type declaration
err?
optional err: Error;

message

message: string;
Inherited from

Error.message

name

name: string;
Inherited from

Error.name

stack?

optional stack: string;
Inherited from

Error.stack

type

type: ErrorType;

The error type. Used to identify the error in the logs.

prepareStackTrace()?

static optional prepareStackTrace: (err, stackTraces) => any;

Optional override for formatting stack traces

See

https://v8.dev/docs/stack-trace-api#customizing-stack-traces

Parameters
ParameterType
errError
stackTracesCallSite[]
Returns

any

Inherited from

Error.prepareStackTrace

stackTraceLimit

static stackTraceLimit: number;
Inherited from

Error.stackTraceLimit

Methods

captureStackTrace()

static captureStackTrace(targetObject, constructorOpt?): void

Create .stack property on a target object

Parameters
ParameterType
targetObjectobject
constructorOpt?Function
Returns

void

Inherited from

Error.captureStackTrace


CredentialsSignin

Can be thrown from the authorize callback of the Credentials provider. When an error occurs during the authorize callback, two things can happen:

  1. The user is redirected to the signin page, with error=CredentialsSignin&code=credentials in the URL. code is configurable.
  2. If you throw this error in a framework that handles form actions server-side, this error is thrown, instead of redirecting the user, so you’ll need to handle.

Extends

Constructors

new CredentialsSignin(message, errorOptions)

new CredentialsSignin(message?, errorOptions?): CredentialsSignin
Parameters
ParameterType
message?string | ErrorOptions
errorOptions?ErrorOptions
Returns

CredentialsSignin

Inherited from

SignInError.constructor

Properties

cause?

optional cause: Record<string, unknown> & {
  err: Error;
};
Type declaration
err?
optional err: Error;
Inherited from

SignInError.cause

code

code: string;

The error code that is set in the code query parameter of the redirect URL.

⚠ NOTE: This property is going to be included in the URL, so make sure it does not hint at sensitive errors.

The full error is always logged on the server, if you need to debug.

Generally, we don’t recommend hinting specifically if the user had either a wrong username or password specifically, try rather something like “Invalid credentials”.

message

message: string;
Inherited from

SignInError.message

name

name: string;
Inherited from

SignInError.name

stack?

optional stack: string;
Inherited from

SignInError.stack

type

type: ErrorType;

The error type. Used to identify the error in the logs.

Inherited from

SignInError.type

kind

static kind: string;
Inherited from

SignInError.kind

prepareStackTrace()?

static optional prepareStackTrace: (err, stackTraces) => any;

Optional override for formatting stack traces

See

https://v8.dev/docs/stack-trace-api#customizing-stack-traces

Parameters
ParameterType
errError
stackTracesCallSite[]
Returns

any

Inherited from

SignInError.prepareStackTrace

stackTraceLimit

static stackTraceLimit: number;
Inherited from

SignInError.stackTraceLimit

type

static type: string;

Methods

captureStackTrace()

static captureStackTrace(targetObject, constructorOpt?): void

Create .stack property on a target object

Parameters
ParameterType
targetObjectobject
constructorOpt?Function
Returns

void

Inherited from

SignInError.captureStackTrace


Account

Usually contains information about the provider being used and also extends TokenSet, which is different tokens returned by OAuth Providers.

Extends

Properties

access_token?

optional readonly access_token: string;
Inherited from

Partial.access_token

authorization_details?

optional readonly authorization_details: AuthorizationDetails[];
Inherited from

Partial.authorization_details

expires_at?

optional expires_at: number;

Calculated value based on TokenEndpointResponse.expires_in.

It is the absolute timestamp (in seconds) when the TokenEndpointResponse.access_token expires.

This value can be used for implementing token rotation together with TokenEndpointResponse.refresh_token.

See

expires_in?

optional readonly expires_in: number;
Inherited from

Partial.expires_in

id_token?

optional readonly id_token: string;
Inherited from

Partial.id_token

provider

provider: string;

Provider’s id for this account. E.g. “google”. See the full list at https://authjs.dev/reference/core/providers

providerAccountId

providerAccountId: string;

This value depends on the type of the provider being used to create the account.

  • oauth/oidc: The OAuth account’s id, returned from the profile() callback.
  • email: The user’s email address.
  • credentials: id returned from the authorize() callback

refresh_token?

optional readonly refresh_token: string;
Inherited from

Partial.refresh_token

scope?

optional readonly scope: string;
Inherited from

Partial.scope

token_type?

optional readonly token_type: Lowercase<string>;

NOTE: because the value is case insensitive it is always returned lowercased

Inherited from

Partial.token_type

type

type: ProviderType;

Provider’s type for this account

userId?

optional userId: string;

id of the user this account belongs to

See

https://authjs.dev/reference/core/adapters#adapteruser


DefaultSession

Extended by

Properties

expires

expires: string;

user?

optional user: User;

Profile

The user info returned from your OAuth provider.

See

https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims

Indexable

[claim: string]: unknown

Properties

address?

optional address: null | {
  country: null | string;
  formatted: null | string;
  locality: null | string;
  postal_code: null | string;
  region: null | string;
  street_address: null | string;
};

birthdate?

optional birthdate: null | string;

email?

optional email: null | string;

email_verified?

optional email_verified: null | boolean;

family_name?

optional family_name: null | string;

gender?

optional gender: null | string;

given_name?

optional given_name: null | string;

id?

optional id: null | string;

locale?

optional locale: null | string;

middle_name?

optional middle_name: null | string;

name?

optional name: null | string;

nickname?

optional nickname: null | string;

phone_number?

optional phone_number: null | string;

picture?

optional picture: any;

preferred_username?

optional preferred_username: null | string;

profile?

optional profile: null | string;

sub?

optional sub: null | string;

updated_at?

optional updated_at: null | string | number | Date;

website?

optional website: null | string;

zoneinfo?

optional zoneinfo: null | string;

Session

The active session of the logged in user.

Extends

Properties

expires

expires: string;
Inherited from

DefaultSession.expires

user?

optional user: User;
Inherited from

DefaultSession.user


SolidAuthConfig

Configure the Auth method.

Example

import Auth, { type AuthConfig } from "@auth/core"
 
export const authConfig: AuthConfig = {...}
 
const request = new Request("https://example.com")
const response = await AuthHandler(request, authConfig)

See

Initialization

Extends

Properties

adapter?

optional adapter: Adapter;

You can use the adapter option to pass in your database adapter.

Inherited from

AuthConfig.adapter

basePath?

optional basePath: string;

The base path of the Auth.js API endpoints.

Default
"/api/auth" in "next-auth"; "/auth" with all other frameworks
Inherited from

AuthConfig.basePath

callbacks?

optional callbacks: {
  jwt: (params) => Awaitable<null | JWT>;
  redirect: (params) => Awaitable<string>;
  session: (params) => Awaitable<Session | DefaultSession>;
  signIn: (params) => Awaitable<string | boolean>;
};

Callbacks are asynchronous functions you can use to control what happens when an action is performed. Callbacks are extremely powerful, especially in scenarios involving JSON Web Tokens as they allow you to implement access controls without a database and to integrate with external databases or APIs.

jwt()?
optional jwt: (params) => Awaitable<null | JWT>;

This callback is called whenever a JSON Web Token is created (i.e. at sign in) or updated (i.e whenever a session is accessed in the client). Anything you return here will be saved in the JWT and forwarded to the session callback. There you can control what should be returned to the client. Anything else will be kept from your frontend. The JWT is encrypted by default via your AUTH_SECRET environment variable.

session callback

Parameters
ParameterTypeDescription
paramsObject-
params.accountnull | AccountContains information about the provider that was used to sign in.
Also includes TokenSet

Note
available when trigger is "signIn" or "signUp"
params.isNewUser?booleanDeprecated
use trigger === "signUp" instead
params.profile?ProfileThe OAuth profile returned from your provider.
(In case of OIDC it will be the decoded ID Token or /userinfo response)

Note
available when trigger is "signIn".
params.session?anyWhen using AuthConfig.session strategy: "jwt", this is the data
sent from the client via the useSession().update method.

⚠ Note, you should validate this data before using it.
params.tokenJWTWhen trigger is "signIn" or "signUp", it will be a subset of JWT,
name, email and image will be included.

Otherwise, it will be the full JWT for subsequent calls.
params.trigger?"update" | "signIn" | "signUp"Check why was the jwt callback invoked. Possible reasons are:
- user sign-in: First time the callback is invoked, user, profile and account will be present.
- user sign-up: a user is created for the first time in the database (when AuthConfig.session.strategy is set to "database")
- update event: Triggered by the useSession().update method.
In case of the latter, trigger will be undefined.
params.userUser | AdapterUserEither the result of the OAuthConfig.profile or the CredentialsConfig.authorize callback.

Note
available when trigger is "signIn" or "signUp".

Resources:
- Credentials Provider
- User database model
Returns

Awaitable<null | JWT>

redirect()?
optional redirect: (params) => Awaitable<string>;

This callback is called anytime the user is redirected to a callback URL (i.e. on signin or signout). By default only URLs on the same host as the origin are allowed. You can use this callback to customise that behaviour.

Documentation

Example
callbacks: {
  async redirect({ url, baseUrl }) {
    // Allows relative callback URLs
    if (url.startsWith("/")) return `${baseUrl}${url}`
 
    // Allows callback URLs on the same origin
    if (new URL(url).origin === baseUrl) return url
 
    return baseUrl
  }
}
Parameters
ParameterTypeDescription
paramsObject-
params.baseUrlstringDefault base URL of site (can be used as fallback)
params.urlstringURL provided as callback URL by the client
Returns

Awaitable<string>

session()?
optional session: (params) => Awaitable<Session | DefaultSession>;

This callback is called whenever a session is checked. (i.e. when invoking the /api/session endpoint, using useSession or getSession). The return value will be exposed to the client, so be careful what you return here! If you want to make anything available to the client which you’ve added to the token through the JWT callback, you have to explicitly return it here as well.

⚠ By default, only a subset (email, name, image) of the token is returned for increased security.

The token argument is only available when using the jwt session strategy, and the user argument is only available when using the database session strategy.

jwt callback

Example
callbacks: {
  async session({ session, token, user }) {
    // Send properties to the client, like an access_token from a provider.
    session.accessToken = token.accessToken
 
    return session
  }
}
Parameters
ParameterType
params{ session: { user: AdapterUser; } & AdapterSession; user: AdapterUser; } & { session: Session; token: JWT; } & { newSession: any; trigger: "update"; }
Returns

Awaitable<Session | DefaultSession>

signIn()?
optional signIn: (params) => Awaitable<string | boolean>;

Controls whether a user is allowed to sign in or not. Returning true continues the sign-in flow. Returning false or throwing an error will stop the sign-in flow and redirect the user to the error page. Returning a string will redirect the user to the specified URL.

Unhandled errors will throw an AccessDenied with the message set to the original error.

AccessDenied

Example
callbacks: {
 async signIn({ profile }) {
  // Only allow sign in for users with email addresses ending with "yourdomain.com"
  return profile?.email?.endsWith("@yourdomain.com")
}
Parameters
ParameterTypeDescription
paramsObject-
params.accountnull | Account-
params.credentials?Record<string, CredentialInput>If Credentials provider is used, it contains the user credentials
params.email?ObjectIf Email provider is used, on the first call, it contains a
verificationRequest: true property to indicate it is being triggered in the verification request flow.
When the callback is invoked after a user has clicked on a sign in link,
this property will not be present. You can check for the verificationRequest property
to avoid sending emails to addresses or domains on a blocklist or to only explicitly generate them
for email address in an allow list.
params.email.verificationRequest?boolean-
params.profile?ProfileIf OAuth provider is used, it contains the full
OAuth profile returned by your provider.
params.userUser | AdapterUser-
Returns

Awaitable<string | boolean>

Inherited from

AuthConfig.callbacks

cookies?

optional cookies: Partial<CookiesOptions>;

You can override the default cookie names and options for any of the cookies used by Auth.js. You can specify one or more cookies with custom properties and missing options will use the default values defined by Auth.js. If you use this feature, you will likely want to create conditional behavior to support setting different cookies policies in development and production builds, as you will be opting out of the built-in dynamic policy.

  • This is an advanced option. Advanced options are passed the same way as basic options, but may have complex implications or side effects. You should try to avoid using advanced options unless you are very comfortable using them.
Default
{}
Inherited from

AuthConfig.cookies

debug?

optional debug: boolean;

Set debug to true to enable debug messages for authentication and database operations.

Default
false
Inherited from

AuthConfig.debug

events?

optional events: {
  createUser: (message) => Awaitable<void>;
  linkAccount: (message) => Awaitable<void>;
  session: (message) => Awaitable<void>;
  signIn: (message) => Awaitable<void>;
  signOut: (message) => Awaitable<void>;
  updateUser: (message) => Awaitable<void>;
};

Events are asynchronous functions that do not return a response, they are useful for audit logging. You can specify a handler for any of these events below - e.g. for debugging or to create an audit log. The content of the message object varies depending on the flow (e.g. OAuth or Email authentication flow, JWT or database sessions, etc), but typically contains a user object and/or contents of the JSON Web Token and other information relevant to the event.

Default
{}
createUser()?
optional createUser: (message) => Awaitable<void>;
Parameters
ParameterType
messageObject
message.userUser
Returns

Awaitable<void>

linkAccount()?
optional linkAccount: (message) => Awaitable<void>;
Parameters
ParameterType
messageObject
message.accountAccount
message.profileUser | AdapterUser
message.userUser | AdapterUser
Returns

Awaitable<void>

session()?
optional session: (message) => Awaitable<void>;

The message object will contain one of these depending on if you use JWT or database persisted sessions:

  • token: The JWT for this session.
  • session: The session object from your adapter.
Parameters
ParameterType
messageObject
message.sessionSession
message.tokenJWT
Returns

Awaitable<void>

signIn()?
optional signIn: (message) => Awaitable<void>;

If using a credentials type auth, the user is the raw response from your credential provider. For other providers, you’ll get the User object from your adapter, the account, and an indicator if the user was new to your Adapter.

Parameters
ParameterType
messageObject
message.accountnull | Account
message.isNewUser?boolean
message.profile?Profile
message.userUser
Returns

Awaitable<void>

signOut()?
optional signOut: (message) => Awaitable<void>;

The message object will contain one of these depending on if you use JWT or database persisted sessions:

  • token: The JWT for this session.
  • session: The session object from your adapter that is being ended.
Parameters
ParameterType
message{ session: undefined | null | void | AdapterSession; } | { token: null | JWT; }
Returns

Awaitable<void>

updateUser()?
optional updateUser: (message) => Awaitable<void>;
Parameters
ParameterType
messageObject
message.userUser
Returns

Awaitable<void>

Inherited from

AuthConfig.events

experimental?

optional experimental: {
  enableWebAuthn: boolean;
};

Use this option to enable experimental features. When enabled, it will print a warning message to the console.

Note

Experimental features are not guaranteed to be stable and may change or be removed without notice. Please use with caution.

Default
{}
enableWebAuthn?
optional enableWebAuthn: boolean;

Enable WebAuthn support.

Default
false
Inherited from

AuthConfig.experimental

jwt?

optional jwt: Partial<JWTOptions>;

JSON Web Tokens are enabled by default if you have not specified an AuthConfig.adapter. JSON Web Tokens are encrypted (JWE) by default. We recommend you keep this behaviour.

Inherited from

AuthConfig.jwt

logger?

optional logger: Partial<LoggerInstance>;

Override any of the logger levels (undefined levels will use the built-in logger), and intercept logs in NextAuth. You can use this option to send NextAuth logs to a third-party logging service.

Example
// /auth.ts
import log from "logging-service"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  logger: {
    error(code, ...message) {
      log.error(code, message)
    },
    warn(code, ...message) {
      log.warn(code, message)
    },
    debug(code, ...message) {
      log.debug(code, message)
    }
  }
})
Default
console
Inherited from

AuthConfig.logger

pages?

optional pages: Partial<PagesOptions>;

Specify URLs to be used if you want to create custom sign in, sign out and error pages. Pages specified will override the corresponding built-in page.

Default
{}
Example
  pages: {
    signIn: '/auth/signin',
    signOut: '/auth/signout',
    error: '/auth/error',
    verifyRequest: '/auth/verify-request',
    newUser: '/auth/new-user'
  }
Inherited from

AuthConfig.pages

prefix?

optional prefix: string;

Defines the base path for the auth routes.

Default
'/api/auth'

providers

providers: Provider[];

List of authentication providers for signing in (e.g. Google, Facebook, Twitter, GitHub, Email, etc) in any order. This can be one of the built-in providers or an object with a custom provider.

Default
[]
Inherited from

AuthConfig.providers

raw?

optional raw: typeof raw;
Inherited from

AuthConfig.raw

redirectProxyUrl?

optional redirectProxyUrl: string;

When set, during an OAuth sign-in flow, the redirect_uri of the authorization request will be set based on this value.

This is useful if your OAuth Provider only supports a single redirect_uri or you want to use OAuth on preview URLs (like Vercel), where you don’t know the final deployment URL beforehand.

The url needs to include the full path up to where Auth.js is initialized.

Note

This will auto-enable the state OAuth2Config.checks on the provider.

Example
"https://authjs.example.com/api/auth"

You can also override this individually for each provider.

Example
GitHub({
  ...
  redirectProxyUrl: "https://github.example.com/api/auth"
})
Default

AUTH_REDIRECT_PROXY_URL environment variable

See also: Guide: Securing a Preview Deployment

Inherited from

AuthConfig.redirectProxyUrl

secret?

optional secret: string | string[];

A random string used to hash tokens, sign cookies and generate cryptographic keys.

To generate a random string, you can use the Auth.js CLI: npx auth secret

Note

You can also pass an array of secrets, in which case the first secret that successfully decrypts the JWT will be used. This is useful for rotating secrets without invalidating existing sessions. The newer secret should be added to the start of the array, which will be used for all new sessions.

Inherited from

AuthConfig.secret

session?

optional session: {
  generateSessionToken: () => string;
  maxAge: number;
  strategy: "jwt" | "database";
  updateAge: number;
};

Configure your session like if you want to use JWT or a database, how long until an idle session expires, or to throttle write operations in case you are using a database.

generateSessionToken()?
optional generateSessionToken: () => string;

Generate a custom session token for database-based sessions. By default, a random UUID or string is generated depending on the Node.js version. However, you can specify your own custom string (such as CUID) to be used.

Default

randomUUID or randomBytes.toHex depending on the Node.js version

Returns

string

maxAge?
optional maxAge: number;

Relative time from now in seconds when to expire the session

Default
2592000 // 30 days
strategy?
optional strategy: "jwt" | "database";

Choose how you want to save the user session. The default is "jwt", an encrypted JWT (JWE) in the session cookie.

If you use an adapter however, we default it to "database" instead. You can still force a JWT session by explicitly defining "jwt".

When using "database", the session cookie will only contain a sessionToken value, which is used to look up the session in the database.

Documentation | Adapter | About JSON Web Tokens

updateAge?
optional updateAge: number;

How often the session should be updated in seconds. If set to 0, session is updated every time.

Default
86400 // 1 day
Inherited from

AuthConfig.session

skipCSRFCheck?

optional skipCSRFCheck: typeof skipCSRFCheck;
Inherited from

AuthConfig.skipCSRFCheck

theme?

optional theme: Theme;

Changes the theme of built-in AuthConfig.pages.

Inherited from

AuthConfig.theme

trustHost?

optional trustHost: boolean;

Auth.js relies on the incoming request’s host header to function correctly. For this reason this property needs to be set to true.

Make sure that your deployment platform sets the host header safely.

Official Auth.js-based libraries will attempt to set this value automatically for some deployment platforms (eg.: Vercel) that are known to set the host header safely.

Inherited from

AuthConfig.trustHost

useSecureCookies?

optional useSecureCookies: boolean;

When set to true then all cookies set by NextAuth.js will only be accessible from HTTPS URLs. This option defaults to false on URLs that start with http:// (e.g. http://localhost:3000) for developer convenience. You can manually set this option to false to disable this security feature and allow cookies to be accessible from non-secured URLs (this is not recommended).

  • This is an advanced option. Advanced options are passed the same way as basic options, but may have complex implications or side effects. You should try to avoid using advanced options unless you are very comfortable using them.

The default is false HTTP and true for HTTPS sites.

Inherited from

AuthConfig.useSecureCookies


User

The shape of the returned object in the OAuth providers’ profile callback, available in the jwt and session callbacks, or the second parameter of the session callback, when using a database.

Extended by

Properties

email?

optional email: null | string;

id?

optional id: string;

image?

optional image: null | string;

name?

optional name: null | string;

GetSessionResult

type GetSessionResult: Promise<Session | null>;

customFetch

const customFetch: unique symbol;

This advanced option allows you to override the default fetch function used by the provider to make requests to the provider’s OAuth endpoints.

It can be used to support corporate proxies, custom fetch libraries, cache discovery endpoints, add mocks for testing, logging, set custom headers/params for non-spec compliant providers, etc.

Example

import { Auth, customFetch } from "@auth/core"
import GitHub from "@auth/core/providers/github"
 
const dispatcher = new ProxyAgent("my.proxy.server")
function proxy(...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {
  return undici(args[0], { ...(args[1] ?? {}), dispatcher })
}
 
const response = await Auth(request, {
  providers: [GitHub({ [customFetch]: proxy })]
})

See


SolidAuth()

SolidAuth(config): {
  GET: Promise<undefined | Response>;
  POST: Promise<undefined | Response>;
}

Setup

Generate an auth secret, then set it as an environment variable:

AUTH_SECRET=your_auth_secret

Creating the API handler

This example uses github, make sure to set the following environment variables:

GITHUB_ID=your_github_oauth_id
GITHUB_SECRET=your_github_oauth_secret
// routes/api/auth/[...solidauth].ts
import { SolidAuth, type SolidAuthConfig } from "@auth/solid-start"
import GitHub from "@auth/core/providers/github"
 
export const authOpts: SolidAuthConfig = {
  providers: [
    GitHub({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET,
    }),
  ],
  debug: false,
}
 
export const { GET, POST } = SolidAuth(authOpts)

Getting the current session

import { getSession } from "@auth/solid-start"
import { createServerData$ } from "solid-start/server"
import { authOpts } from "~/routes/api/auth/[...solidauth]"
 
export const useSession = () => {
  return createServerData$(
    async (_, { request }) => {
      return await getSession(request, authOpts)
    },
    { key: () => ["auth_user"] }
  )
}
 
// useSession returns a resource:
const session = useSession()
const loading = session.loading
const user = () => session()?.user

Protected Routes

When Using SSR

When using SSR, it is recommended to create a Protected component that will trigger suspense using the Show component. It should look like this:

// components/Protected.tsx
import { type Session } from "@auth/core/types";
import { getSession } from "@auth/solid-start";
import { Component, Show } from "solid-js";
import { useRouteData } from "solid-start";
import { createServerData$, redirect } from "solid-start/server";
import { authOpts } from "~/routes/api/auth/[...solidauth]";
 
const Protected = (Comp: IProtectedComponent) => {
  const routeData = () => {
    return createServerData$(
      async (_, event) => {
        const session = await getSession(event.request, authOpts);
        if (!session || !session.user) {
          throw redirect("/");
        }
        return session;
      },
      { key: () => ["auth_user"] }
    );
  };
 
  return {
    routeData,
    Page: () => {
      const session = useRouteData<typeof routeData>();
      return (
        <Show when={session()} keyed>
          {(sess) => <Comp {...sess} />}
        </Show>
      );
    },
  };
};
 
type IProtectedComponent = Component<Session>;
 
export default Protected;

It can be used like this:

// routes/protected.tsx
import Protected from "~/components/Protected";
 
export const { routeData, Page } = Protected((session) => {
  return (
    <main class="flex flex-col gap-2 items-center">
      <h1>This is a protected route</h1>
    </main>
  );
});
 
export default Page;

When Using CSR

When using CSR, the Protected component will not work as expected and will cause the screen to flash. To fix this, a Solid-Start middleware is used:

// entry-server.tsx
import { Session } from "@auth/core";
import { getSession } from "@auth/solid-start";
import { redirect } from "solid-start";
import {
  StartServer,
  createHandler,
  renderAsync,
} from "solid-start/entry-server";
import { authOpts } from "./routes/api/auth/[...solidauth]";
 
const protectedPaths = ["/protected"]; // add any route you wish in here
 
export default createHandler(
  ({ forward }) => {
    return async (event) => {
      if (protectedPaths.includes(new URL(event.request.url).pathname)) {
        const session = await getSession(event.request, authOpts);
        if (!session) {
          return redirect("/");
        }
      }
      return forward(event);
    };
  },
  renderAsync((event) => <StartServer event={event} />)
);

And now a protected route can be created:

// routes/protected.tsx
export default () => {
  return (
    <main class="flex flex-col gap-2 items-center">
      <h1>This is a protected route</h1>
    </main>
  );
};

The CSR method should also work when using SSR, the SSR method shouldn’t work when using CSR

Parameters

ParameterType
configSolidAuthConfig

Returns

{
  GET: Promise<undefined | Response>;
  POST: Promise<undefined | Response>;
}

GET()

Parameters
ParameterType
eventany
Returns

Promise<undefined | Response>

POST()

Parameters
ParameterType
eventany
Returns

Promise<undefined | Response>


getSession()

getSession(req, options): GetSessionResult

Parameters

ParameterType
reqRequest
optionsOmit<AuthConfig, "raw">

Returns

GetSessionResult

Auth.js © Balázs Orbán and Team - 2024