Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve Server Component Logging with unstable_after #246

Open
sam3d opened this issue Nov 24, 2024 · 1 comment
Open

Improve Server Component Logging with unstable_after #246

sam3d opened this issue Nov 24, 2024 · 1 comment

Comments

@sam3d
Copy link

sam3d commented Nov 24, 2024

Current Issues

  1. Manual Flush API Management

    • Developers must remember to call log.flush() explicitly
    • Poor handling of early returns/exits
    • Requires error handling in every exit path to ensure logs are saved
  2. Performance Impact

    • Blocking behavior: Must wait for log flush and HTTP request completion
    • Delays server component response unnecessarily

Proposed Solution

Use Next.js's unstable_after API to handle log flushing automatically after request completion, similar to middleware's waitUntil.

Current Approach (Problematic)

import { Logger } from 'next-axiom';

export default async function ServerComponent() {
  const log = new Logger();
  log.info('User logged in', { userId: 42 });

  // Early return example - logs would be lost
  if (someCondition) {
    return <h1>Early Exit</h1>;
  }

  await log.flush(); // Blocking operation
  return <h1>Logged in</h1>;
}

Proposed Approach

import { Logger } from 'next-axiom';
import { unstable_after as after } from "next/server"

export default async function ServerComponent() {
  const log = new Logger();
  after(log.flush); // Non-blocking, executes after request lifecycle
  log.info('User logged in', { userId: 42 });

  // Early return example - logs will still be flushed
  if (someCondition) {
    return <h1>Early Exit</h1>;
  }

  return <h1>Logged in</h1>;
}

Benefits

  • Graceful handling of early exits
  • Non-blocking execution
  • Simplified developer experience
  • Consistent log flushing regardless of return path

Discussion Points

  • Should this pattern be integrated into the library as a dedicated API?
  • Or should it be documented as a recommended practice?
  • Consider adding to documentation for server component logging best practices
@dasfmi
Copy link
Collaborator

dasfmi commented Dec 13, 2024

hi @sam3d , looks like this is stable now in Next 15.1. I believe we could update your documentation to reflect this as a good practice for Server Components but not sure how can we wrap RSC to achieve this from within next-axiom library.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants