payloadcms/payload · error · APIError

Invalid path segment. Only alphanumeric characters and under

Error message

Invalid path segment. Only alphanumeric characters and underscores are permitted.

What it means

Thrown by sanitizePathSegment when a path segment fails the regex /^\w+$/ (only letters, digits, underscore). This guards dynamically-built query paths (e.g. JSON-path or column-path construction) against path-traversal/injection, since a segment is interpolated into a SQL/JSON path.

Source

Thrown at packages/drizzle/src/utilities/sanitizePathSegment.ts:12

import { APIError } from 'payload'

/**
 * Validates that a path segment contains only allowed characters (word characters: [a-zA-Z0-9_]).
 *
 * @throws {APIError} if the segment contains characters outside /^[\w]+$/
 */
const SAFE_PATH_SEGMENT_REGEX = /^\w+$/

export const sanitizePathSegment = (segment: string): string => {
  if (!SAFE_PATH_SEGMENT_REGEX.test(segment)) {
    throw new APIError(
      'Invalid path segment. Only alphanumeric characters and underscores are permitted.',
      400,
    )
  }
  return segment
}

View on GitHub (pinned to 00c58b35c0)

Solutions

  1. Whitelist-validate the segment against /^\w+$/ before passing it into the query builder.
  2. Map user-facing identifiers (slugs with hyphens) to internal word-only keys before use.
  3. Reject or encode any segment containing dots, slashes, spaces, or punctuation.

Example fix

// before
const seg = req.query.field // 'user.email' -> fails
where: { [seg]: { equals: val } }
// after
const seg = req.query.field
if (!/^\w+$/.test(seg)) throw new APIError('invalid field', 400)
where: { [seg]: { equals: val } }
Defensive patterns

Strategy: validation

Validate before calling

const SEG = /^\w+$/
function assertSafeSegment(s) {
  if (!SEG.test(s)) throw new Error('Path segment contains invalid characters')
}

Type guard

const isSafeSegment = (s) => /^\w+$/.test(s)

Prevention

When it happens

Trigger: Passing a path segment derived from user input (URL param, query param) that contains a dot, slash, space, quote, or any non-word character into a query path that goes through sanitizePathSegment.

Common situations: Reflecting req.query fields directly into a where-clause path; using a slug containing hyphens as a path segment.

Related errors


AI-assisted analysis of payloadcms/payload@00c58b35c0 (2026-08-12). Data as JSON: /api/errors/9a8ba7a1200d30de. Report an issue: GitHub.