Next.js developer in Oslo

Next.js for businesses in Oslo, delivered remotely by one developer.

Next.js developer

My place in the WordPress community

  • I have had a wordpress.org account since 2006.
  • I contributed to WordPress core for versions 7.0 and 7.1.
  • I maintain 30 plugins on wordpress.org.
  • I organise and speak at WordCamps.
  • I have attended every WordCamp Europe from 2017 to 2026.

My WordPress.org profile

A Next.js application that lets Norwegians log in does not store passwords. It sends the browser to ID-porten, the public login service run by the Norwegian Digitalisation Agency, Digdir, and receives a signed id_token. A server that calls a protected public API gets its access token from Maskinporten instead. I am Mariusz Szatkowski, writing code from Gdynia for clients across Europe, and the authentication layer of a Next.js application is what this page is about.

Birkelunden park in Oslo

Birkelunden park in Oslo, photographed by Leonhard Lenz and released under CC0, from Wikimedia Commons.

Everything below comes from the Digdir documentation at docs.digdir.no and from the discovery documents that ID-porten and Maskinporten publish themselves. I am not a lawyer. Which assurance level a service needs is decided by the owner of the service and its legal basis, not by the developer.

#What is ID-porten and how does a Next.js app use it?

ID-porten uses the authorization code flow from OpenID Connect Core 1.0, built on OAuth 2.0. The client must be registered in advance. The application redirects the browser to the authorize endpoint with client_id, redirect_uri, scope, acr_values, response_type=code, ui_locales, state, nonce, code_challenge and code_challenge_method. After login the browser returns with a code, and the server exchanges it at the token endpoint together with the code_verifier.

That split suits the App Router. The login start and the callback are Route Handlers, the code exchange runs on the server, and no token reaches a client component. The Next.js authentication guide describes the same boundary: cookies are set on the server, session logic is marked server-only, and a Data Access Layer verifies the session close to the data.

#Is PKCE mandatory for ID-porten?

The Digdir documentation says all clients must use PKCE, and that ID-porten will as a rule reject an authentication request without it. Only S256 is supported. The code verifier must be at least 43 and at most 128 characters, and the challenge must be sent without padding. The documentation lists a self-service option to downgrade a client for old software, but a new Next.js application has no reason to use it.

The verifier must survive the redirect, which is a design choice in Next.js. Store it with the state and nonce in one short-lived, HttpOnly, Secure cookie set by the login Route Handler, or in a server-side store keyed by state. A sketch of the start of the flow:

// app/login/route.ts (sketch)
import { randomBytes, createHash } from 'node:crypto'
import { cookies } from 'next/headers'
import { NextResponse } from 'next/server'

export async function GET() {
  const meta = await getMetadata() // cached discovery document
  const verifier = randomBytes(48).toString('base64url') // 64 characters
  const challenge = createHash('sha256').update(verifier).digest('base64url')
  const state = randomBytes(16).toString('base64url')
  const nonce = randomBytes(16).toString('base64url')

  ;(await cookies()).set('oidc', JSON.stringify({ verifier, state, nonce }), {
    httpOnly: true, secure: true, sameSite: 'lax', path: '/', maxAge: 600,
  })

  const url = new URL(meta.authorization_endpoint)
  url.search = new URLSearchParams({
    client_id: process.env.IDPORTEN_CLIENT_ID!,
    redirect_uri: process.env.IDPORTEN_REDIRECT_URI!,
    response_type: 'code',
    scope: 'openid',
    acr_values: 'idporten-loa-substantial',
    state, nonce,
    code_challenge: challenge,
    code_challenge_method: 'S256',
  }).toString()
  return NextResponse.redirect(url)
}

The callback comes back as a top-level GET navigation, so the Lax cookie arrives with it. That is why this flow, unlike a form POST callback, works with the cookie options the Next.js guide recommends.

#Where do the endpoint addresses come from?

From the metadata. The documentation lists the issuer https://test.idporten.no for test and https://idporten.no for production, each with /.well-known/openid-configuration. It strongly recommends dynamic configuration so that a change of signing certificate does not interrupt the service, and says the metadata should be cached, typically for 24 hours.

The test discovery document I read lists the authorize endpoint on login.test.idporten.no, the token endpoint on test.idporten.no, a pushed authorization request endpoint, jwks_uri, end_session_endpoint and S256 as the only challenge method. Supported client authentication methods include client_secret_basic, client_secret_post, private_key_jwt and none. The guide recommends private_key_jwt for high-security services.

#How do I validate the id_token?

The id_token documentation says the client must validate the token under OpenID Connect Core section 3.1.7, and additionally check that the acr is high enough for the service. In a Route Handler that means verifying the signature against the keys at jwks_uri, then checking iss, aud (your client_id), exp, the nonce you stored, and acr.

// inside app/callback/route.ts (sketch)
import { createRemoteJWKSet, jwtVerify } from 'jose'

const jwks = createRemoteJWKSet(new URL(meta.jwks_uri))
const { payload } = await jwtVerify(idToken, jwks, {
  issuer: meta.issuer,
  audience: process.env.IDPORTEN_CLIENT_ID!,
})
if (payload.nonce !== saved.nonce) throw new Error('nonce')
if (payload.acr !== 'idporten-loa-substantial') throw new Error('acr')

The discovery document also says authorization_response_iss_parameter_supported is true, so the callback carries an iss parameter. Compare it with the issuer before you exchange the code.

The documented claims include sub, pid, sid, nonce, acr, aud, auth_time, exp, iat and jti. The amr value can change over time, and the documentation says the client should not validate it.

#Which acr value should I ask for?

The discovery document lists idporten-loa-low, idporten-loa-substantial, idporten-loa-substantial-limited, idporten-loa-high and three eIDAS values: eidas-loa-low, eidas-loa-substantial and eidas-loa-high. The guide example uses idporten-loa-substantial, and the documentation tells the client to check the returned acr against what it asked for.

Choose per screen, like a bank does. A newsletter preference page and a tax submission do not need the same level. Do not hardcode one string in five places: keep the required level next to the route that needs it.

#Which identifier should become the user key?

The documentation separates two claims. sub is a pairwise identifier: one client always gets the same value for a given user, and different clients get different values. pid is the Norwegian national ID number, and the documentation notes that some eID providers, for example for foreign users, may not supply it. ID-porten also documents pseudonymised login for cases where a client should not receive the national ID number.

The Next.js guide says a session payload should carry only the minimum unique data and should not contain personal data such as a phone number or an email address. I would key the account on sub, and fetch pid only if the agenda requires it, on the server, never into a client component. Whether you may store pid at all is a question for your data protection adviser.

#How do sessions and logout work?

The guide describes the ID-porten single sign-on session: at most 120 minutes from first authentication and expiring after 30 minutes of inactivity. Access and refresh tokens are independent of that session and stay valid until they expire.

Logout is where a stateless cookie session breaks down. To log out, redirect the browser to the end_session_endpoint in the metadata. ID-porten then terminates its session and sends front-channel logout requests to the other clients. The logout documentation says clients cannot expect their own cookie to be included in that notification, because browsers limit third-party cookies, and tells clients to store the sid value from the id_token. The sid is included only if the client is registered with frontchannel_logout_session_required.

So the session needs a server-side record that maps sid to a session. This is the database session the Next.js guide describes, with an encrypted session ID in the cookie. A pure JWT cookie cannot be revoked by a request that does not carry it.

#What does Maskinporten add for server-to-server calls?

Maskinporten is for machine-to-machine access, not for citizens. The guide says it accepts only signed JWTs as grants. The client posts grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer and an assertion to the token endpoint and authenticates with private_key_jwt, using either an enterprise certificate or its own asymmetric key. Client secrets are not accepted.

The assertion claims are aud (the Maskinporten issuer), iss (your client_id), scope, iat, exp and jti. The guide says exp minus iat may be at most 120 seconds, recommends one scope per token, and says a JWT cannot be reused. The metadata at https://test.maskinporten.no/.well-known/oauth-authorization-server lists the issuer as https://test.maskinporten.no/ and the token endpoint as https://test.maskinporten.no/token.

// app/lib/maskinporten.ts (sketch)
import 'server-only'
import { SignJWT, importPKCS8 } from 'jose'

export async function getToken(scope: string) {
  const key = await importPKCS8(process.env.MASKINPORTEN_KEY!, 'RS256')
  const assertion = await new SignJWT({ scope })
    .setProtectedHeader({ alg: 'RS256', kid: process.env.MASKINPORTEN_KID! })
    .setIssuer(process.env.MASKINPORTEN_CLIENT_ID!)
    .setAudience('https://test.maskinporten.no/')
    .setIssuedAt()
    .setExpirationTime('100s')
    .setJti(crypto.randomUUID())
    .sign(key)

  const res = await fetch('https://test.maskinporten.no/token', {
    method: 'POST',
    headers: { 'content-type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
      assertion,
    }),
  })
  return res.json()
}

The server-only import keeps the key out of client bundles, a pattern the Next.js guide uses for session code. A Maskinporten token is requested from a Route Handler or a Server Action and never from the browser.

#How do I register a client?

Clients are registered in Samarbeidsportalen, by self-service, through the self-service API, or for ID-porten by email to Digdir. The registration documentation lists integration types, among them idporten for login, hardcoded to the openid profile scopes, and maskinporten for server-to-server. The type cannot be changed after creation, and a scope restricted to one type cannot be added to another.

For Maskinporten, the guide says organisations that accepted Digdir’s terms can self-register a user for the test environment with their organisation’s email domain. Production requires an ID-porten login, and an authorised person in the organisation approves which national identity numbers get access.

#What needs an answer before the first commit?

  • Which integration type and scopes the application needs, and who approves production access.
  • The acr level for each protected route.
  • Whether the account key is sub, and whether pid is needed at all.
  • Where the sid mapping lives, since logout depends on it.
  • How the Maskinporten key is stored, rotated and kept out of the repository.
  • Which API scopes the receiving API owner has granted.

#What I deliver for an Oslo team

I write the login, callback, logout and session layers, the Maskinporten token helper and the screens around them, in strict TypeScript. You get the repository, a runbook that lists every client setting and environment variable, and tests that run against the test environments. The legal basis for processing national ID numbers stays with your organisation.

Work runs remotely and in writing. If you have an Oslo project that needs ID-porten or Maskinporten, send the scope through the contact page. The first written estimate is free, and the Next.js developer page describes the wider scope.

See also in Norway

Need this service: Next.js developer in Oslo?

Describe your project by e-mail. I reply within 24 hours.

Describe your project

Explore other WordPress services and knowledge base