# Better Stack Legacy Next.js client

## Start logging in 3 steps

This is a legacy documentation for Next.js application using **Pages Router**.

Using **App Router**? See [current version of Next.js docs](https://betterstack.com/docs/logs/javascript/nextjs/) instead.

### 1. Install

Install Logtail Next.js NPM package:

```bash
[label Install Logtail Next.js]
npm install @logtail/next@^0.1.0
```

### 2. Setup

Set `LOGTAIL_SOURCE_TOKEN` and `LOGTAIL_URL` environment variables:

```bash
[label Set environment variable]
export LOGTAIL_SOURCE_TOKEN="$SOURCE_TOKEN"
export LOGTAIL_URL="https://$INGESTING_HOST"
```

Set up Better Stack Next.js client in `next.config.js`:

```javascript
[label Wrap Next.js config with Logtail]
const { withLogtail } = require('@logtail/next');

module.exports = withLogtail({
  // Your existing config
});
```

Import Better Stack Next.js logger:

```javascript
[label Import Logtail logger]
const { log } = require('@logtail/next');
```

### 3. Start logging 🎉

Use structured logging in client, edge, or server-side files:

```javascript
[label Send logs to Logtail]
log.error("Something bad happened.");
log.info("Log message with structured logging.", {
    item: "Orange Soda",
    price: 100.00
});
```

You should see your logs in [Better Stack → Live tail](https://telemetry.betterstack.com/team/0/tail ";_blank").

[warning]
**Next.js version 12.1.4 or higher is required.**  
[/warning]

## Need help?

Please let us know at hello@betterstack.com.  
We're happy to help! 🙏

## Advanced usage

### Handlers

Get logger with **automatic log flushing** and built-in **exception logging**.  
Wrap your Next.js route handlers with Better Stack:

```javascript
[label Logging in handlers]
const { withLogtail, LogtailAPIRequest } = require('@logtail/next');

async function handler(req: LogtailAPIRequest, res: NextApiResponse) {
  req.log.info("Hello Logtail!");

  res.status(200).text("OK");
}

export default withLogtail(handler);
```

### Log levels

Better Stack Next.js client provides four log levels: `debug`, `info`, `warn`, and `error`.  
Stop sending `debug` logs to Better Stack:

```sh
[label Don't send debug logs] 
export LOGTAIL_LOG_LEVEL=info
```

### Server-side props

Take advantage of **automatic log flushing** and built-in **exception logging**.   
Wrap your server-side props with Better Stack:

```javascript
[label Server-side props]
const { withLogtailGetServerSideProps } = require('@logtail/next');
export const getServerSideProps = withLogtailGetServerSideProps(
  async ({ req, log }) => {
    log.info("Hello Logtail!");
    return {
      props: {
      },
    }
  }
);
```