⚠
vite-plugin-ssr has been renamed Vike, see migration guide.

Auth.js

Auth.js (previously known as NextAuth.js) can be used with vite-plugin-ssr.

Examples

process.env.NEXTAUTH_URL

To access environment variables on the client-side, such as process.env.NEXTAUTH_URL, we can use vite.config.js#define or vite.config.js#envPrefix.

⚠
Don't add NEXTAUTH_ to envPrefix as it would leak NEXTAUTH_SECRET.

See also:

We can use process.env as usual for server (e.g. Express.js) code. (Since server code isn't processed by Vite.)

Fetch polyfill for getSession()

In order to use Auth.js's getSession() on the server-side, we need to globally install a fetch polyfill.

A polyfill isn't needed if we use getSession() only on the client-side, or if we use Node.js 18 which natively supports fetch().

We can use node-fetch to patch the global object:

// server.js

// Only install the polyfill on the server (e.g. Express.js). Browsers already implement
// `fetch()` natively and it would be wasteful to load the polyfill on the browser-side.

// Use node-fetch@2 instead of node-fetch@3 if your `package.json#type` isn't `"module"`.
// Or some other `fetch()` polyfill, e.g. `cross-fetch`.
import fetch, { Headers, Request, Response } from 'node-fetch'

if (!globalThis.fetch) {
  globalThis.fetch = fetch
  globalThis.Headers = Headers
  globalThis.Request = Request
  globalThis.Response = Response
}

See also